I have a problem using simpledialog.askstring from tkinter, it opens two pop up windows, one of them is the regular one to input a value, but the other is a blank window that freezes completely and you have to force the cloosure of the window, enter image description hereas shown in the image in the link. I'm using spyder.
What could be happening?
This is what I have so far:
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QApplication, QMainWindow, QComboBox,
QLabel, QPushButton, QGroupBox
import tkinter as tk
from tkinter import simpledialog
from PIL import ImageGrab
import sys
import cv2
import numpy as np
# import imageToString
import pyperclip
import webbrowser
import pytesseract
pytesseract.pytesseract.tesseract_cmd =
r"C:\Users\amc\AppData\Local\Programs\Tesseract-OCR\tesseract.exe"
class Communicate(QObject):
snip_saved = pyqtSignal()
class MyWindow(QMainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__()
self.win_width = 340
self.win_height = 200
self.setGeometry(50, 50, self.win_width, self.win_height)
self.setWindowTitle("PSD Generator")
self.initUI()
def initUI(self):
#Define buttons
self.searchOpen = QPushButton(self)
self.searchOpen.setText("Digitilize Graph")
self.searchOpen.move(10,75)
self.searchOpen.setFixedSize(150,40)
self.searchOpen.clicked.connect(self.snip_graph_clicked)
self.copyPartNum = QPushButton(self)
self.copyPartNum.setText("Snip Table")
self.copyPartNum.move((self.win_width/2)+10, 75)
self.copyPartNum.setFixedSize(150,40)
self.copyPartNum.clicked.connect(self.snip_table_clicked)
self.notificationBox = QGroupBox("Notification Box", self)
self.notificationBox.move(10,135)
self.notificationBox.setFixedSize(self.win_width-20,55)
self.notificationText = QLabel(self)
self.notificationText.move(20, 145)
self.reset_notif_text()
def snip_graph_clicked(self):
self.snipWin = SnipWidget(False, True, self)
self.snipWin.notification_signal.connect(self.reset_notif_text)
self.snipWin.show()
self.notificationText.setText("Snipping... Press ESC to quit snipping")
self.update_notif()
def snip_table_clicked(self):
self.snipWin = SnipWidget(True, False, self)
self.snipWin.notification_signal.connect(self.reset_notif_text)
self.snipWin.show()
self.notificationText.setText("Snipping... Press ESC to quit snipping")
self.update_notif()
def reset_notif_text(self):
self.notificationText.setText("Idle...")
self.update_notif()
def define_notif_text(self, msg):
print('notification was sent')
self.notificationText.setText('notification was sent')
self.update_notif()
def update_notif(self):
self.notificationText.move(20, 155)
self.notificationText.adjustSize()
class SnipWidget(QMainWindow):
notification_signal = pyqtSignal()
def __init__(self, copy_table, scan_graph, parent):
super(SnipWidget, self).__init__()
self.copy_table = copy_table
self.scan_graph = scan_graph
root = tk.Tk()# instantiates window
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
self.setGeometry(0, 0, screen_width, screen_height)
self.setWindowTitle(' ')
self.begin = QtCore.QPoint()
self.end = QtCore.QPoint()
self.setWindowOpacity(0.3)
self.is_snipping = False
QtWidgets.QApplication.setOverrideCursor(
QtGui.QCursor(QtCore.Qt.CrossCursor)
)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.c = Communicate()
self.show()
if self.copy_table == True:
# the input dialog
BH_Ref = simpledialog.askstring(title="New PSD",prompt="Borehole Number Ref:")
Depth = simpledialog.askstring(title="New PSD",prompt="Sample depth (m):")
self.c.snip_saved.connect(self.searchAndOpen)
if self.scan_graph == True:
# the input dialog
BH_Ref = simpledialog.askstring(title="New PSD",prompt="Borehole Number Ref:")
Depth = simpledialog.askstring(title="New PSD",prompt="Sample depth (m):")
self.c.snip_saved.connect(self.IdAndCopy)
def paintEvent(self, event):
if self.is_snipping:
brush_color = (0, 0, 0, 0)
lw = 0
opacity = 0
else:
brush_color = (128, 128, 255, 128)
lw = 3
opacity = 0.3
self.setWindowOpacity(opacity)
qp = QtGui.QPainter(self)
qp.setPen(QtGui.QPen(QtGui.QColor('black'), lw))
qp.setBrush(QtGui.QColor(*brush_color))
qp.drawRect(QtCore.QRect(self.begin, self.end))
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Escape:
print('Quit')
QtWidgets.QApplication.restoreOverrideCursor();
self.notification_signal.emit()
self.close()
event.accept()
def mousePressEvent(self, event):
self.begin = event.pos()
self.end = self.begin
self.update()
def mouseMoveEvent(self, event):
self.end = event.pos()
self.update()
def mouseReleaseEvent(self, event):
x1 = min(self.begin.x(), self.end.x())
y1 = min(self.begin.y(), self.end.y())
x2 = max(self.begin.x(), self.end.x())
y2 = max(self.begin.y(), self.end.y())
self.is_snipping = True
self.repaint()
QtWidgets.QApplication.processEvents()
img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
self.is_snipping = False
self.repaint()
QtWidgets.QApplication.processEvents()
img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2GRAY)
self.snipped_image = img
QtWidgets.QApplication.restoreOverrideCursor();
self.c.snip_saved.emit()
self.close()
self.msg = 'snip complete'
self.notification_signal.emit()
def searchAndOpen(self):
img_str = self.imgToStr(self.snipped_image)
msg_str = f'Text in snip is {img_str}'
def IdAndCopy(self):
img_str = self.imgToStr(self.snipped_image)
pyperclip.copy(img_str)
def find_str(self, image_data):
img = image_data
h,w = np.shape(img)
asp_ratio = float(w/h)
img_width = 500
img_height = int(round(img_width/asp_ratio))
desired_image_size = (img_width,img_height)
img_resized = cv2.resize(img, desired_image_size)
imgstr = str(pytesseract.image_to_string(img_resized))
print(imgstr)
return imgstr
def imgToStr(self, image):
# img_str = imageToString.main(image)
img_str = self.find_str(image)
return img_str
def window():
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
window()
Related
This question already has an answer here:
What is the difference between an opencv BGR image and its reverse version RGB image[:,:,::-1]?
(1 answer)
Closed 2 years ago.
I have a custom QLabel class which is called ImageLabel to show images and video stream. I want to update the image with the setPixmap() method but it doesn't update the image correctly.
Note: StreamThread method is related to the video stream and I don't use it to update the image for now.
Here is the distorted image:
Main class:
import sys
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget, QPushButton, QHBoxLayout
from ImageLabel import ImageLabel
from Stream_Thread import Stream_Thread
import cv2
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.init_UI()
def init_UI(self):
self.setFixedSize(690, 530)
self.image_lbl = ImageLabel()
# start the video stream of selected camera
th = Stream_Thread()
th.set_index(1)
th.changePixmap.connect(self.setImage, Qt.QueuedConnection)
th.start()
btn_cnt = QPushButton("Continue")
btn_pa = QPushButton("Pause")
hbox = QHBoxLayout()
hbox.addWidget(btn_cnt)
hbox.addWidget(btn_pa)
vbox = QVBoxLayout()
vbox.addWidget(self.image_lbl)
vbox.addLayout(hbox)
self.setLayout(vbox)
btn_pa.clicked.connect(lambda: self.btn_pa_clicked(th))
self.show()
#pyqtSlot(QImage)
def setImage(self, image):
self.image_lbl.pixmap = QPixmap.fromImage(image).scaled(720, 540)
self.image_lbl.setPixmap(QPixmap.fromImage(image).scaled(720, 540))
def btn_pa_clicked(self, th):
th.terminate() # terminates the video stream
image = cv2.imread("img/49.jpg", cv2.COLOR_BGR2RGB) # self.image_lbl.pixmap
# image = image.toImage()
if image is not None:
(h, w, c) = image.shape
qimage = QImage(image.data, h, w, 3 * h, QImage.Format_RGB888)
self.image_lbl.pixmap = QPixmap.fromImage(qimage)
#self.image_lbl.setPixmap(QPixmap.fromImage(qimage))
self.image_lbl.repaint()
def main():
app = QApplication(sys.argv)
main_form = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
StreamThread class:
import cv2
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtGui import QImage
#https://stackoverflow.com/a/44404713/13080899
class Stream_Thread(QThread):
changePixmap = pyqtSignal(QImage)
def __init__(self):
super(Stream_Thread, self).__init__()
self.ref = False #refresh flag
def set_index(self, index = 0):
self.index = int(index)
def refresh(self):
self.ref = True
self.capt.open(self.index)
def run(self):
self.capt = cv2.VideoCapture(self.index, cv2.CAP_DSHOW)
while(True):
ret, frame = self.capt.read()
if ret:
rbgImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, ch = rbgImage.shape
bytesPerLine = ch*w
convertToQtFormat = QImage(rbgImage.data, w, h, bytesPerLine, QImage.Format_RGB888)
p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
self.changePixmap.emit(p)
ImageLabel class:
from PyQt5 import QtGui, QtCore
from PyQt5.QtCore import Qt, QSize, pyqtSignal, QObject, QPoint, pyqtSlot
from PyQt5.QtWidgets import QLabel
class Communicate(QObject):
cor_update = pyqtSignal()
cor_curr = pyqtSignal()
class ImageLabel(QLabel):
def __init__(self, width=720, height=540):
super(ImageLabel, self).__init__()
self.setMouseTracking(True)
self.pixmap = QtGui.QPixmap("img/im.jpg")
#### initialize coordinates ####
self.x1 = 0
self.y1 = 0
self.x_curr = 0
self.y_curr = 0
self.x2 = 0
self.y2 = 0
##### enable state to allow user for drawing
self.enable_labelling = False
##### enable state to track coordinates for drawing
self.enable_cor = False
################################
self.source = Communicate()
def paintEvent(self, event):
qp = QtGui.QPainter(self)
qp.drawPixmap(self.rect(), self.pixmap)
if self.enable_labelling == True:
self.paintRect(event, qp)
qp.end()
def paintRect(self, event, qp):
br = QtGui.QBrush(QtGui.QColor(50, 255, 255, 40))
qp.setBrush(br)
if self.enable_cor == True:
qp.drawRect(QtCore.QRect(QPoint(self.x1, self.y1), QSize(self.x_curr - self.x1, self.y_curr - self.y1)))
else:
qp.drawRect(QtCore.QRect(QPoint(self.x1, self.y1), QSize(self.x2 - self.x1, self.y2 - self.y1)))
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton and self.enable_labelling == True:
self.x1 = event.x()
self.y1 = event.y()
self.enable_cor = True
self.source.cor_update.emit()
def mouseMoveEvent(self, event):
self.x_curr = event.x()
self.y_curr = event.y()
self.source.cor_curr.emit()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton and self.enable_labelling == True:
self.x2 = event.x()
self.y2 = event.y()
self.source.cor_update.emit()
self.enable_cor = False
Instead of opening image by Imread and convert it to QImage, open it by QImage and convert the format that should solve your problem. Use of:
image = QImage("img/49.jpg");
image = image.convertToFormat(QImage.Format_RGB888);
this is psudo code and not tested, maybe some modification are needed.
This question already has answers here:
Painting background on QGraphicsView using drawBackground
(1 answer)
How to enable Pan and Zoom in a QGraphicsView
(3 answers)
How to put an image in QGraphicsView's scrollbar area?
(1 answer)
Closed 3 years ago.
I'm wondering how to set QgraphicsView's background Image.
In this painter program, the background is just white color.
I want to load some image(jpg, png, .. whatever) and set it as painter's background.
and after painting it, I want to just save painting (not include background, just what i painted.)
how can i do this? please help me.
import sys
from PyQt5.QtCore import *
from PyQt5.QtCore import Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import (QApplication, QCheckBox, QGridLayout, QGroupBox,
QPushButton, QVBoxLayout, QWidget, QSlider)
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
class CWidget(QWidget):
def __init__(self):
super().__init__()
# 전체 폼 박스
formbox = QHBoxLayout()
self.setLayout(formbox)
# 좌, 우 레이아웃박스
left = QVBoxLayout()
right = QVBoxLayout()
# 그룹박스2
gb = QGroupBox('펜 설정')
left.addWidget(gb)
grid = QGridLayout()
gb.setLayout(grid)
label = QLabel('펜 색상')
grid.addWidget(label, 1, 0)
self.pencolor = QColor(0, 0, 0)
self.penbtn = QPushButton()
self.penbtn.setStyleSheet('background-color: rgb(0,0,0)')
self.penbtn.clicked.connect(self.showColorDlg)
grid.addWidget(self.penbtn, 1, 1)
label = QLabel('펜 굵기')
grid.addWidget(label, 2, 0)
self.slider = QSlider(Qt.Horizontal)
self.slider.setMinimum(3)
self.slider.setMaximum(21)
self.slider.setValue(5)
self.slider.setFocusPolicy(Qt.StrongFocus)
self.slider.setTickPosition(QSlider.TicksBothSides)
self.slider.setTickInterval(1)
self.slider.setSingleStep(1)
grid.addWidget(self.slider)
# 그룹박스4
gb = QGroupBox('지우개')
left.addWidget(gb)
hbox = QHBoxLayout()
gb.setLayout(hbox)
self.checkbox = QCheckBox('지우개')
self.checkbox.stateChanged.connect(self.checkClicked)
hbox.addWidget(self.checkbox)
left.addStretch(1)
# 우 레이아웃 박스에 그래픽 뷰 추가
self.view = CView(self)
right.addWidget(self.view)
# 전체 폼박스에 좌우 박스 배치
formbox.addLayout(left)
formbox.addLayout(right)
formbox.setStretchFactor(left, 0)
formbox.setStretchFactor(right, 1)
self.setGeometry(100, 100, 800, 500)
def checkClicked(self):
pass
def createExampleGroup(self):
groupBox = QGroupBox("Slider Example")
slider = QSlider(Qt.Horizontal)
slider.setFocusPolicy(Qt.StrongFocus)
slider.setTickPosition(QSlider.TicksBothSides)
slider.setTickInterval(10)
slider.setSingleStep(1)
vbox = QVBoxLayout()
vbox.addWidget(slider)
vbox.addStretch(1)
groupBox.setLayout(vbox)
return groupBox
def showColorDlg(self):
# 색상 대화상자 생성
color = QColorDialog.getColor()
sender = self.sender()
# 색상이 유효한 값이면 참, QFrame에 색 적용
self.pencolor = color
self.penbtn.setStyleSheet('background-color: {}'.format(color.name()))
# QGraphicsView display QGraphicsScene
class CView(QGraphicsView):
def __init__(self, parent):
super().__init__(parent)
self.scene = QGraphicsScene()
self.setScene(self.scene)
self.items = []
self.start = QPointF()
self.end = QPointF()
self.setRenderHint(QPainter.HighQualityAntialiasing)
def moveEvent(self, e):
rect = QRectF(self.rect())
rect.adjust(0, 0, -2, -2)
self.scene.setSceneRect(rect)
def mousePressEvent(self, e):
if e.button() == Qt.LeftButton:
# 시작점 저장
self.start = e.pos()
self.end = e.pos()
def mouseMoveEvent(self, e):
# e.buttons()는 정수형 값을 리턴, e.button()은 move시 Qt.Nobutton 리턴
if e.buttons() & Qt.LeftButton:
self.end = e.pos()
if self.parent().checkbox.isChecked():
pen = QPen(QColor(255, 255, 255), 10)
path = QPainterPath()
path.moveTo(self.start)
path.lineTo(self.end)
self.scene.addPath(path, pen)
self.start = e.pos()
return None
pen = QPen(self.parent().pencolor, self.parent().slider.value())
# Path 이용
path = QPainterPath()
path.moveTo(self.start)
path.lineTo(self.end)
self.scene.addPath(path, pen)
# 시작점을 다시 기존 끝점으로
self.start = e.pos()
def open(self):
fileName, _ = QFileDialog.getOpenFileName(self, "Open File",
QDir.currentPath())
if fileName:
image = QImage(fileName)
if image.isNull():
QMessageBox.information(self, "Image Viewer",
"Cannot load %s." % fileName)
return
self.imageLabel.setPixmap(QPixmap.fromImage(image))
self.scaleFactor = 1.0
self.printAct.setEnabled(True)
self.fitToWindowAct.setEnabled(True)
self.updateActions()
if not self.fitToWindowAct.isChecked():
self.imageLabel.adjustSize()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = CWidget()
w.show()
sys.exit(app.exec_())
You can create an instance of QGraphicsPixmapItem and add it to the scene, here is an example:
import sys
from PyQt5.QtCore import *
from PyQt5.QtCore import Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import (QApplication, QCheckBox, QGridLayout, QGroupBox,
QPushButton, QVBoxLayout, QWidget, QSlider)
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
class CWidget(QWidget):
def __init__(self):
super().__init__()
# 전체 폼 박스
formbox = QHBoxLayout()
self.setLayout(formbox)
# 좌, 우 레이아웃박스
left = QVBoxLayout()
right = QVBoxLayout()
# 그룹박스2
gb = QGroupBox('펜 설정')
left.addWidget(gb)
grid = QGridLayout()
gb.setLayout(grid)
label = QLabel('펜 색상')
grid.addWidget(label, 1, 0)
self.pencolor = QColor(0, 0, 0)
self.penbtn = QPushButton()
self.penbtn.setStyleSheet('background-color: rgb(0,0,0)')
self.penbtn.clicked.connect(self.showColorDlg)
grid.addWidget(self.penbtn, 1, 1)
label = QLabel('펜 굵기')
grid.addWidget(label, 2, 0)
self.slider = QSlider(Qt.Horizontal)
self.slider.setMinimum(3)
self.slider.setMaximum(21)
self.slider.setValue(5)
self.slider.setFocusPolicy(Qt.StrongFocus)
self.slider.setTickPosition(QSlider.TicksBothSides)
self.slider.setTickInterval(1)
self.slider.setSingleStep(1)
grid.addWidget(self.slider)
# 그룹박스4
gb = QGroupBox('지우개')
left.addWidget(gb)
hbox = QHBoxLayout()
gb.setLayout(hbox)
self.checkbox = QCheckBox('지우개')
self.checkbox.stateChanged.connect(self.checkClicked)
hbox.addWidget(self.checkbox)
left.addStretch(1)
# 우 레이아웃 박스에 그래픽 뷰 추가
self.view = CView(self)
right.addWidget(self.view)
# 전체 폼박스에 좌우 박스 배치
formbox.addLayout(left)
formbox.addLayout(right)
formbox.setStretchFactor(left, 0)
formbox.setStretchFactor(right, 1)
self.setGeometry(100, 100, 800, 500)
def checkClicked(self, state):
self.view.stretch(state)
def createExampleGroup(self):
groupBox = QGroupBox("Slider Example")
slider = QSlider(Qt.Horizontal)
slider.setFocusPolicy(Qt.StrongFocus)
slider.setTickPosition(QSlider.TicksBothSides)
slider.setTickInterval(10)
slider.setSingleStep(1)
vbox = QVBoxLayout()
vbox.addWidget(slider)
vbox.addStretch(1)
groupBox.setLayout(vbox)
return groupBox
def showColorDlg(self):
# 색상 대화상자 생성
color = QColorDialog.getColor()
sender = self.sender()
# 색상이 유효한 값이면 참, QFrame에 색 적용
self.pencolor = color
self.penbtn.setStyleSheet('background-color: {}'.format(color.name()))
# QGraphicsView display QGraphicsScene
class CView(QGraphicsView):
def __init__(self, parent):
super().__init__(parent)
self.scene = QGraphicsScene()
self.setScene(self.scene)
self.items = []
self.start = QPointF()
self.end = QPointF()
self.backgroundImage = None
self.graphicsPixmapItem = None
self.setRenderHint(QPainter.HighQualityAntialiasing)
self.open()
def moveEvent(self, e):
rect = QRectF(self.rect())
rect.adjust(0, 0, -2, -2)
self.scene.setSceneRect(rect)
def mousePressEvent(self, e):
if e.button() == Qt.LeftButton:
# 시작점 저장
self.start = e.pos()
self.end = e.pos()
def mouseMoveEvent(self, e):
# e.buttons()는 정수형 값을 리턴, e.button()은 move시 Qt.Nobutton 리턴
if e.buttons() & Qt.LeftButton:
self.end = e.pos()
if self.parent().checkbox.isChecked():
pen = QPen(QColor(255, 255, 255), 10)
path = QPainterPath()
path.moveTo(self.start)
path.lineTo(self.end)
self.scene.addPath(path, pen)
self.start = e.pos()
return None
pen = QPen(self.parent().pencolor, self.parent().slider.value())
# Path 이용
path = QPainterPath()
path.moveTo(self.start)
path.lineTo(self.end)
self.scene.addPath(path, pen)
# 시작점을 다시 기존 끝점으로
self.start = e.pos()
def stretch(self, state):
self._set_image(state == 2)
def open(self):
fileName, _ = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath(), filter='Images (*.png *.xpm *.jpg)')
if fileName:
image = QImage(fileName)
if image.isNull():
QMessageBox.information(self, "Image Viewer",
"Cannot load %s." % fileName)
return
self.backgroundImage = fileName
self._set_image(False)
def _set_image(self, stretch: bool):
tempImg = QPixmap(self.backgroundImage)
if stretch:
tempImg = tempImg.scaled(self.scene.width(), self.scene.height())
if self.graphicsPixmapItem is not None:
self.scene.removeItem(self.graphicsPixmapItem)
self.graphicsPixmapItem = QGraphicsPixmapItem(tempImg)
self.scene.addItem(self.graphicsPixmapItem)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = CWidget()
w.show()
sys.exit(app.exec_())
This program is a trafficlight program but i want to put a gif on the right space of the window that will show a walking man gif when the color is green and a stop gif when in red or yellow so I tried to use QMovie which I get mixed results and still ended up in an error or the gif won't appear at the window can you please help me?
from itertools import cycle
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer,Qt,QPoint
from PyQt5.QtWidgets import QApplication,QMainWindow
from PyQt5.QtGui import QPainter,QColor,QMovie
class TrafficLight(QMainWindow):
def __init__(self,parent = None):
super(TrafficLight, self).__init__(parent)
self.setWindowTitle("TrafficLight ")
self.traffic_light_color1 = cycle(\[
QColor('red'),
QColor('gray'),
QColor('gray')
\])
self.traffic_light_color2 = cycle(\[
QColor('gray'),
QColor('yellow'),
QColor('gray')
\])
self.traffic_light_color3 = cycle(\[
QColor('gray'),
QColor('gray'),
QColor('green')
\])
self._current_color1 = next(self.traffic_light_color1)
self._current_color2 = next(self.traffic_light_color2)
self._current_color3 = next(self.traffic_light_color3)
timer = QTimer(self, timeout=self.change_color)
x = 0
if x == 0 :
self.movie1 = QMovie("Walking-man2[enter image description here][1].gif")
self.movie1.frameChanged.connect(self.repaint)
self.movie1.start()
timer.start(30*100)
x = 1
elif x == 1 :
self.movie1 = QMovie("tenor(1).gif")
self.movie1.frameChanged.connect(self.repaint)
self.movie1.start()
timer.start(10*100)
x = 2
elif x == 2:
self.movie1 = QMovie("tenor(1).gif")
self.movie1.frameChanged.connect(self.repaint)
self.movie1.start()
timer.start(40*100)
x = 0
self.resize(700, 510)
#QtCore.pyqtSlot()
def change_color(self):
self._current_color1 = next(self.traffic_light_color1)
self._current_color2 = next(self.traffic_light_color2)
self._current_color3 = next(self.traffic_light_color3)
self.update()
def paintEvent(self, event):
p1 = QPainter(self)
p1.setBrush(self._current_color1)
p1.setPen(Qt.black)
p1.drawEllipse(QPoint(125, 125), 50, 50)
p2 = QPainter(self)
p2.setBrush(self._current_color2)
p2.setPen(Qt.black)
p2.drawEllipse(QPoint(125, 250),50,50)
p3 = QPainter(self)
p3.setBrush(self._current_color3)
p3.setPen(Qt.black)
p3.drawEllipse(QPoint(125, 375),50,50)
currentFrame = self.movie1.currentPixmap()
frameRect = currentFrame.rect()
frameRect.moveCenter(self.rect().center())
if frameRect.intersects(event.rect()):
painter = QPainter(self)
painter.drawPixmap(frameRect.left(), frameRect.top(), currentFrame)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = TrafficLight()
w.show()
sys.exit(app.exec_())
The logic of changing one state to another can be implemented with a Finite State Machine (FSM), and fortunately Qt implements it using The State Machine Framework:
from functools import partial
from PyQt5 import QtCore, QtGui, QtWidgets
class LightWidget(QtWidgets.QWidget):
def __init__(self, color, parent=None):
super(LightWidget, self).__init__(parent)
self._state = False
self._color = color
self.setFixedSize(150, 150)
#QtCore.pyqtSlot()
def turnOn(self):
self._state = True
self.update()
#QtCore.pyqtSlot()
def turnOff(self):
self._state = False
self.update()
def paintEvent(self, event):
color = self._color if self._state else QtGui.QColor('gray')
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setPen(QtCore.Qt.black)
painter.setBrush(color)
painter.drawEllipse(self.rect())
class TrafficLightWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(TrafficLightWidget, self).__init__(parent)
hlay = QtWidgets.QHBoxLayout(self)
container = QtWidgets.QWidget()
container.setStyleSheet('''background-color : black''')
vlay = QtWidgets.QVBoxLayout(container)
self.m_red = LightWidget(QtGui.QColor("red"))
self.m_yellow = LightWidget(QtGui.QColor("yellow"))
self.m_green = LightWidget(QtGui.QColor("green"))
vlay.addWidget(self.m_red)
vlay.addWidget(self.m_yellow)
vlay.addWidget(self.m_green)
hlay.addWidget(container, alignment=QtCore.Qt.AlignCenter)
self.label = QtWidgets.QLabel("Test", alignment=QtCore.Qt.AlignCenter)
hlay.addWidget(self.label, 1)
red_to_yellow = createLightState(self.m_red, 30*1000, partial(self.change_gif, "gif_red.gif"))
yellow_to_green = createLightState(self.m_yellow, 20*1000, partial(self.change_gif, "gif_yellow.gif"))
green_to_yellow = createLightState(self.m_green, 40*1000, partial(self.change_gif, "gif_green.gif"))
yellow_to_red = createLightState(self.m_yellow, 20*1000, partial(self.change_gif, "gif_yellow.gif"))
red_to_yellow.addTransition(red_to_yellow.finished, yellow_to_green)
yellow_to_green.addTransition(yellow_to_green.finished, green_to_yellow)
green_to_yellow.addTransition(green_to_yellow.finished, yellow_to_red)
yellow_to_red.addTransition(yellow_to_red.finished, red_to_yellow)
machine = QtCore.QStateMachine(self)
machine.addState(red_to_yellow)
machine.addState(yellow_to_green)
machine.addState(green_to_yellow)
machine.addState(yellow_to_red)
machine.setInitialState(red_to_yellow)
machine.start()
#QtCore.pyqtSlot()
def change_gif(self, gif):
last_movie = self.label.movie()
movie = QtGui.QMovie(gif)
self.label.setMovie(movie)
movie.start()
if last_movie is not None:
last_movie.deleteLater()
def createLightState(light, duration, callback):
lightState = QtCore.QState()
timer = QtCore.QTimer(
lightState,
interval=duration,
singleShot=True
)
timing = QtCore.QState(lightState)
timing.entered.connect(light.turnOn)
timing.entered.connect(callback)
timing.entered.connect(timer.start)
timing.exited.connect(light.turnOff)
done = QtCore.QFinalState(lightState)
timing.addTransition(timer.timeout, done)
lightState.setInitialState(timing)
return lightState
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = TrafficLightWidget()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
Though the answer ain't as fancy as eyllanesc's... You can make the ellipse depend on a variable color, then change the stored variable color and call update(). The gif can be displayed using a label
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer,Qt,QPoint
from PyQt5.QtWidgets import QApplication,QMainWindow
from PyQt5.QtGui import QPainter,QColor,QMovie
class TrafficLight(QtWidgets.QWidget):
def __init__(self,parent = None):
super(TrafficLight, self).__init__(parent)
self.setWindowTitle("TrafficLight ")
layout = QtWidgets.QHBoxLayout()
self.setLayout(layout)
self.lblGif = QtWidgets.QLabel()
layout.addSpacing(300)
layout.addWidget(self.lblGif)
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.changeLight)
self.timer.start(3000)
self.resize(700, 510)
self.x = 0
self.changeLight()
def changeLight(self):
if self.x == 0 :
self.color1 = QColor('red')
self.color2 = QColor('grey')
self.color3 = QColor('grey')
self.loadGif('wait.gif')
self.x = 1
elif self.x == 1 :
self.color1 = QColor('grey')
self.color2 = QColor('yellow')
self.color3 = QColor('grey')
self.loadGif('almost.gif')
self.x = 2
elif self.x == 2:
self.color1 = QColor('grey')
self.color2 = QColor('grey')
self.color3 = QColor('green')
self.loadGif('walk.gif')
self.x = 0
self.update()
def loadGif(self, path):
movie = QtGui.QMovie(path)
self.lblGif.setMovie(movie)
movie.start()
def paintEvent(self, event):
p1 = QPainter(self)
p1.setBrush(self.color1)
p1.setPen(Qt.black)
p1.drawEllipse(QPoint(125, 125), 50, 50)
p1.end()
p2 = QPainter(self)
p2.setBrush(self.color2)
p2.setPen(Qt.black)
p2.drawEllipse(QPoint(125, 250),50,50)
p2.end()
p3 = QPainter(self)
p3.setBrush(self.color3)
p3.setPen(Qt.black)
p3.drawEllipse(QPoint(125, 375),50,50)
p3.end()
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = TrafficLight()
w.show()
sys.exit(app.exec_())
The purpose of this code is to have a square that appears in a canvas for some time and is then erased. I understand that all painting events must be handled by the overloaded function paintEvent.
However, first, the squares are not being drawn and I believe, that the times at which the squares are supposed to be drawn and erased are not being respected either. My guess is this happens due to the frequency at which the event appears.
I already tried to call QPaintEvent under the functions drawApple and eraseApple. What am I missing?
import sys, random
import numpy as np
import math
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QTimer
from PyQt4.QtCore import QRect
from PyQt4.QtGui import QPaintEvent
class Game(QtGui.QMainWindow):
def __init__(self):
super(Game, self).__init__()
self.initUI()
def initUI(self):
palette = QtGui.QPalette()
palette.setColor(QtGui.QPalette.Background, QtCore.Qt.white)
self.setPalette(palette)
self.tboard = Board(self)
self.setCentralWidget(self.tboard)
self.resize(400, 400)
self.center()
self.setWindowTitle('Game')
self.show()
def center(self):
screen = QtGui.QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
class Board(QtGui.QFrame):
BoardWidth = 400
BoardHeight = 400
SquareWidth = 15
SquareHeight = 15
Speed = 10000
def __init__(self, parent):
super(Board, self).__init__(parent)
#self.setAutoFillBackground(True)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.timer_draw = QtCore.QTimer()
self.timer_draw.timeout.connect(self.drawApple)
self.timer_draw.start(self.Speed)
self.timer_draw.setInterval(self.Speed)
self.timer_erase = QtCore.QTimer()
self.timer_erase.timeout.connect(self.eraseApple)
self.timer_erase.start(self.Speed + self.Speed/2)
self.timer_erase.setInterval(self.Speed)
self.apple_color = QtCore.Qt.red
self.bkg_color = QtCore.Qt.white
self.draw_apple = False
self.x_apple = 0
self.y_apple = 0
self.rect = QRect(self.x_apple, self.y_apple, self.SquareWidth, self.SquareHeight)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
print "Paint Event?"
if self.draw_apple == True:
print "Draw"
self.apple_color = QtCore.Qt.red
else:
print "Do not draw"
self.apple_color = self.bkg_color
painter.setPen(self.apple_color)
painter.drawRect(self.rect)
def drawApple(self):
print "Enters drawApple"
self.x_apple = np.random.randint(0, math.floor(self.BoardWidth/self.SquareWidth)) * self.SquareWidth
self.y_apple = np.random.randint(0, math.floor(self.BoardHeight/self.SquareHeight)) * self.SquareHeight
self.draw_apple == True
def eraseApple(self):
print "Enters eraseApple"
self.draw_apple == True
def main():
app = QtGui.QApplication([])
game = Game()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You should call the update() function as it calls paintEvent(). Also I recommend using a single timer for that task. You only have to deny the variable draw_apple to change state.
import sys, random
import numpy as np
import math
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QTimer, QRect
from PyQt4.QtGui import QPaintEvent
class Game(QtGui.QMainWindow):
def __init__(self):
super(Game, self).__init__()
self.initUI()
def initUI(self):
palette = QtGui.QPalette()
palette.setColor(QtGui.QPalette.Background, QtCore.Qt.white)
self.setPalette(palette)
self.tboard = Board(self)
self.setCentralWidget(self.tboard)
self.resize(400, 400)
self.center()
self.setWindowTitle('Game')
self.show()
def center(self):
screen = QtGui.QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
class Board(QtGui.QFrame):
BoardWidth = 400
BoardHeight = 400
SquareWidth = 15
SquareHeight = 15
Speed = 10000
def __init__(self, parent):
super(Board, self).__init__(parent)
#self.setAutoFillBackground(True)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.timer_draw = QtCore.QTimer(self)
self.timer_draw.timeout.connect(self.drawApple)
self.timer_draw.start(self.Speed)
self.apple_color = QtCore.Qt.red
self.draw_apple = False
self.x_apple = 0
self.y_apple = 0
self.drawApple()
def paintEvent(self, event):
painter = QtGui.QPainter(self)
print "Paint Event?"
if self.draw_apple == True:
print "Draw"
self.apple_color = QtCore.Qt.red
else:
print "Do not draw"
self.apple_color = QtCore.Qt.white
painter.setPen(self.apple_color)
painter.drawRect(self.rect)
def drawApple(self):
self.draw_apple = not self.draw_apple
self.x_apple = np.random.randint(0, math.floor(self.BoardWidth/self.SquareWidth)) * self.SquareWidth
self.y_apple = np.random.randint(0, math.floor(self.BoardHeight/self.SquareHeight)) * self.SquareHeight
self.rect = QRect(self.x_apple, self.y_apple, self.SquareWidth, self.SquareHeight)
self.update()
def main():
app = QtGui.QApplication([])
game = Game()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I have this app written in pyqt. You can view the source at http://www.pasteall.org/62739/python It takes screen shots of the desktop. what I want to know is how to make it also take a screen shot of a certain area on the screen like window's snipping tool can do (http://sjcblogs.sanjac.edu/its/files/2011/09/Snipping-Tool-selection-types1.jpg and gilsmethod.wpengine.netdna-cdn.com/images/snipping-tool-windows-73.png). How do I write this?
Thank you in advance!
You should use
img = QPixmap.grabWindow(QApplication.desktop().winId(), x, y, width, height)
The pyqt distro has a very good python example of screeshoting with pyqt. The C++ code of the example, easily converted to Python, is at http://doc.qt.io/qt-4.8/qt-desktop-screenshot-example.html
Install following packages:
pip install pillow opencv-python pyside2
Run the following code:
import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
import numpy as np
import cv2
from PIL import ImageGrab
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
if not MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(1000, 1000)
sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QSize(1000, 1000))
MainWindow.setMaximumSize(QSize(16777215, 16777215))
MainWindow.setTabShape(QTabWidget.Rounded)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName(u"centralwidget")
sizePolicy1 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
sizePolicy1.setHorizontalStretch(0)
sizePolicy1.setVerticalStretch(0)
sizePolicy1.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy1)
self.centralwidget.setMinimumSize(QSize(1000, 1000))
self.gridLayout = QGridLayout(self.centralwidget)
self.gridLayout.setObjectName(u"gridLayout")
self.pushButton_area = QPushButton(self.centralwidget)
self.pushButton_area.setObjectName(u"pushButton_area")
self.pushButton_area.setMinimumSize(QSize(800, 0))
self.gridLayout.addWidget(self.pushButton_area, 0, 0, 1, 1)
self.label = QLabel(self.centralwidget)
self.label.setObjectName(u"label")
sizePolicy2 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
sizePolicy2.setHorizontalStretch(0)
sizePolicy2.setVerticalStretch(0)
sizePolicy2.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy2)
self.label.setMinimumSize(QSize(800, 800))
self.label.setMaximumSize(QSize(4096, 4096))
self.gridLayout.addWidget(self.label, 2, 0, 2, 1)
self.pushButton_full = QPushButton(self.centralwidget)
self.pushButton_full.setObjectName(u"pushButton_full")
self.pushButton_full.setMinimumSize(QSize(800, 0))
self.gridLayout.addWidget(self.pushButton_full, 1, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"Snipping Tool", None))
MainWindow.setAccessibleName(QCoreApplication.translate("MainWindow", u"Snipping Tool", None))
self.pushButton_area.setText(QCoreApplication.translate("MainWindow", u"Select Area", None))
self.pushButton_full.setText(QCoreApplication.translate("MainWindow", u"Fullscreen", None))
# Refer to https://github.com/harupy/snipping-tool
class SnippingWidget(QWidget):
is_snipping = False
def __init__(self, parent=None, app=None):
super(SnippingWidget, self).__init__()
self.parent = parent
self.setWindowFlags(Qt.WindowStaysOnTopHint)
self.screen = app.primaryScreen()
self.setGeometry(0, 0, self.screen.size().width(), self.screen.size().height())
self.begin = QPoint()
self.end = QPoint()
self.onSnippingCompleted = None
def fullscreen(self):
img = ImageGrab.grab(bbox=(0, 0, self.screen.size().width(), self.screen.size().height()))
try:
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
except:
img = None
if self.onSnippingCompleted is not None:
self.onSnippingCompleted(img)
def start(self):
SnippingWidget.is_snipping = True
self.setWindowOpacity(0.3)
QApplication.setOverrideCursor(QCursor(Qt.CrossCursor))
self.show()
def paintEvent(self, event):
if SnippingWidget.is_snipping:
brush_color = (128, 128, 255, 100)
lw = 3
opacity = 0.3
else:
self.begin = QPoint()
self.end = QPoint()
brush_color = (0, 0, 0, 0)
lw = 0
opacity = 0
self.setWindowOpacity(opacity)
qp = QPainter(self)
qp.setPen(QPen(QColor('black'), lw))
qp.setBrush(QColor(*brush_color))
rect = QRectF(self.begin, self.end)
qp.drawRect(rect)
def mousePressEvent(self, event):
self.begin = event.pos()
self.end = self.begin
self.update()
def mouseMoveEvent(self, event):
self.end = event.pos()
self.update()
def mouseReleaseEvent(self, event):
SnippingWidget.is_snipping = False
QApplication.restoreOverrideCursor()
x1 = min(self.begin.x(), self.end.x())
y1 = min(self.begin.y(), self.end.y())
x2 = max(self.begin.x(), self.end.x())
y2 = max(self.begin.y(), self.end.y())
self.repaint()
QApplication.processEvents()
img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
try:
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
except:
img = None
if self.onSnippingCompleted is not None:
self.onSnippingCompleted(img)
self.close()
class MainWindow(QMainWindow):
useQThread = True
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setAcceptDrops(True)
self.snippingWidget = SnippingWidget(app=QApplication.instance())
self.snippingWidget.onSnippingCompleted = self.onSnippingCompleted
self.ui.pushButton_area.clicked.connect(self.snipArea)
self.ui.pushButton_full.clicked.connect(self.snipFull)
self._pixmap = None
def onSnippingCompleted(self, frame):
self.setWindowState(Qt.WindowActive)
if frame is None:
return
image = QImage(frame, frame.shape[1], frame.shape[0], frame.strides[0], QImage.Format_RGB888)
pixmap = QPixmap.fromImage(image)
self._pixmap = self.resizeImage(pixmap)
self.ui.label.setPixmap(self._pixmap)
def snipArea(self):
self.setWindowState(Qt.WindowMinimized)
self.snippingWidget.start()
def snipFull(self):
self.setWindowState(Qt.WindowMinimized)
self.snippingWidget.fullscreen()
def dragEnterEvent(self, event):
event.acceptProposedAction()
def dropEvent(self, event):
urls = event.mimeData().urls()
filename = urls[0].toLocalFile()
self.loadFile(filename)
self.decodeFile(filename)
event.acceptProposedAction()
def resizeImage(self, pixmap):
lwidth = self.ui.label.width()
pwidth = pixmap.width()
lheight = self.ui.label.height()
pheight = pixmap.height()
wratio = pwidth * 1.0 / lwidth
hratio = pheight * 1.0 / lheight
if pwidth > lwidth or pheight > lheight:
if wratio > hratio:
lheight = pheight / wratio
else:
lwidth = pwidth / hratio
scaled_pixmap = pixmap.scaled(lwidth, lheight)
return scaled_pixmap
else:
return pixmap
def showMessageBox(self, title, content):
msgBox = QMessageBox()
msgBox.setWindowTitle(title)
msgBox.setText(content)
msgBox.exec_()
def closeEvent(self, event):
msg = "Close the app?"
reply = QMessageBox.question(self, 'Message',
msg, QMessageBox.Yes, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()