Python, tkinter, multiprocessing Variable name not defined problem - python-multiprocessing

from multiprocessing import Process
from tkinter import *
def th():
p = Process(target=Button1)
p.start()
class Button1:
def __init__(self):
btn1.config(state="disabled")
btn1.update()
if __name__ == "__main__":
root = Tk()
root.title("test")
root.resizable(False, False)
btn1 = Button(root, text="시작", width=10, height=5, command=th)
btn1.grid(row=0, column=0, sticky=N+E+W+S, padx=5, pady=5)
root.mainloop()
btn1.config(state="disabled")
NameError: name 'btn1' is not defined
I would appreciate it if you could tell me how to solve it.
I want the button to be disabled when pressed using multi processing.

Related

PyQt5 input text can't be executed as code in QPlainTextEdit

I have a QMainWindow which contains a QPlainTextEdit and a button with clicked even connected. When user finishes text input and press the button, I just want to execute user input for example "1+1". I should get "2", but it is "1+1". Very appreciated for your reply, thanks!
import sys
from PyQt5.QtWidgets import QMainWindow, QPushButton, \
QApplication, QVBoxLayout, QPlainTextEdit, QWidget
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setFixedSize(600, 600)
l_layout = QVBoxLayout()
self.edit = QPlainTextEdit()
self.edit.setFixedSize(400, 300)
self.edit1 = QPlainTextEdit()
self.edit1.setFixedSize(100, 100)
self.btn = QPushButton('Test')
self.btn.clicked.connect(self.press)
l_layout.addWidget(self.edit)
l_layout.addWidget(self.edit1)
l_layout.addWidget(self.btn)
dummy_widget = QWidget()
dummy_widget.setLayout(l_layout)
self.setCentralWidget(dummy_widget)
def press(self):
text = self.edit.toPlainText()
try:
code = """print(text)"""
exec(code)
except Exception as e:
print('not ok!')
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
You should evaluate the input text and then print it, like so:
def press(self):
text = self.edit.toPlainText()
try:
print(eval(text))
except Exception as e:
print('not ok!')
Pay attention, because eval() use can lead to security issues (people executing python code on your app). Make sure your input is sanitized.

PyQt5 Signal Between Classes Causing Lockup

I'm trying to send signals between classes, which works fine from the HMI class to the WorkerThread class, but causes a program lockup, or infinite loop, when WorkerThread tries to connect to a signal from the HMI class.
import sys
import time
import PyQt5
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QWidget, QApplication
from Home import Ui_HomeWin # PyQt5 Designer window
class WorkerThread(QThread):
hmiHandlesThis = PyQt5.QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super(WorkerThread, self).__init__(parent)
self.counter = 0
# this attempted connection causes a lockup
self.HMI_Thread = HMI() # appears to be a recursive loop
self.HMI_Thread.updateGlobals.connect(self.update_global_widgets)
def run(self):
while True:
time.sleep(0.5)
print('Doing a bunch of other stuff: {}'.format(self.counter))
self.counter += 1
def build_a_command(self):
print('building a command...')
name = 'pbAutoMode'
# example command
command = name + '.setStyleSheet("QPushButton{ background-color: rgb(0, 0, 255); }")'
self.hmiHandlesThis.emit(command)
def update_global_widgets(self):
print('update some global widgets')
class HMI(QWidget):
updateGlobals = PyQt5.QtCore.pyqtSignal(name='updateGlobals')
def __init__(self, parent=None):
super(HMI, self).__init__(parent)
self.HomeWin = QtWidgets.QDialog()
self.HomeWin.setWindowFlags(QtCore.Qt.FramelessWindowHint)
ui = Ui_HomeWin()
ui.setupUi(self.HomeWin)
self.HomeWin.show()
# this connection works
self.workerThread = WorkerThread()
self.workerThread.hmiHandlesThis.connect(self.on_new_command)
self.workerThread.start()
def on_new_command(self, command):
print('New command is: {}'.format(command))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = HMI()
sys.exit(app.exec_())~~~
I've tried placing the signal definitions inside the init functions, with no difference.
With Dennis Jensen's help, i've been able to get this running properly. I'm posting the working snippet here as an example of 'proper' thread building and the passing of signals.
import sys
import time
import PyQt5
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QObject, QThread
from PyQt5.QtWidgets import QWidget, QApplication
from Home import Ui_HomeWin # a PyQt5 Designer window
class WorkerThread(QObject):
hmiHandlesThis = PyQt5.QtCore.pyqtSignal(str, str)
def __init__(self, parent=None):
super(WorkerThread, self).__init__(parent)
self.counter = 0
def processRun(self):
while True:
time.sleep(0.5)
print('Doing a bunch of other stuff: {}'.format(self.counter))
self.counter += 1
def update_global_widgets(self):
print('update some global widgets')
def build_a_command(self):
print('building a command...')
name = 'pbAutoMode'
# example command
command = name + '.setStyleSheet("QPushButton{ background-color: rgb(0, 0, 255); }")'
self.hmiHandlesThis.emit(name, command)
class HMI(QWidget):
updateGlobals = PyQt5.QtCore.pyqtSignal(name='updateGlobals')
def __init__(self, parent=None):
super(HMI, self).__init__(parent)
self.HomeWin = QtWidgets.QDialog()
self.HomeWin.setWindowFlags(QtCore.Qt.FramelessWindowHint)
ui = Ui_HomeWin()
ui.setupUi(self.HomeWin)
self.HomeWin.show()
self.EstablishThread()
def EstablishThread(self):
# Create the Object from Class
self.Worker = WorkerThread()
# Assign the Database Signals to Slots
self.Worker.hmiHandlesThis.connect(self.on_new_command)
# Create the Thread
self.ThredHolder = QThread()
# Move the Listener to the Thread
self.Worker.moveToThread(self.ThredHolder)
# Assign the Listener Starting Function to the Thread Call
self.ThredHolder.started.connect(self.Worker.processRun)
# Start the Thread which launches Listener.Connect( )
self.ThredHolder.start()
def on_new_command(self):
print('Handling new command...')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = HMI()
sys.exit(app.exec_())
Thanks Dennis!

pyqt5 videowidget not showing in layout

I am writing a program with pyqt5 where pressing a button first cycles through some pictures then cycles through some videos.
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *
import glob
import argparse
import sys
class MainWindow(QMainWindow):
def __init__(self,args):
super(MainWindow, self).__init__()
self.setWindowTitle('Navon test')
self.setWindowFlags(Qt.FramelessWindowHint)
# exit option for the menu bar File menu
self.exit = QAction('Exit', self)
self.exit.setShortcut('Ctrl+q')
# message for the status bar if mouse is over Exit
self.exit.setStatusTip('Exit program')
# newer connect style (PySide/PyQT 4.5 and higher)
self.exit.triggered.connect(app.quit)
self.setWindowIcon(QIcon('icon.ico'))
self.centralwidget = CentralWidget(args)
self.setCentralWidget(self.centralwidget)
def keyPressEvent(self, QKeyEvent):
if QKeyEvent.key() == Qt.Key_Escape:
QCoreApplication.instance().quit()
self.centralwidget.startvid()
class CentralWidget(QWidget):
def __init__(self,args):
super(CentralWidget, self).__init__()
self.layout = QVBoxLayout()
self.layout.setAlignment(Qt.AlignCenter)
self.setLayout(self.layout)
self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface)
self.vw = QVideoWidget()
self.player.setVideoOutput(self.vw)
def startvid(self):
self.layout.addWidget(self.vw)
url= QUrl.fromLocalFile(glob.glob("videos/*")[0])
content= QMediaContent(url)
self.player.setMedia(content)
self.player.setVideoOutput(self.vw)
self.player.play()
if __name__== "__main__":
parser = argparse.ArgumentParser()
#~ parser.add_argument("-nb","--nobox",action="store_true", help="do not wait for the box connection")
args = parser.parse_args()
app = QApplication(sys.argv)
mainwindow = MainWindow(args)
#~ mainwindow.showFullScreen()
mainwindow.show()
sys.exit(app.exec_())
I tried to paste the minimal code. The thing is, I press the button nothing shows, although I used examples like this one PyQt5 - Can't play video using QVideoWidget to test if playing the video is ok, and these work. It's as if it is not adding the widget to the layout or something. Any idea what might be wrong?
I had to use QGraphicsView to achieve what I wanted, here is a fix:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *
import glob
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle('Navon test')
self.setWindowFlags(Qt.FramelessWindowHint)
# exit option for the menu bar File menu
self.exit = QAction('Exit', self)
self.exit.setShortcut('Ctrl+q')
# message for the status bar if mouse is over Exit
self.exit.setStatusTip('Exit program')
# newer connect style (PySide/PyQT 4.5 and higher)
self.exit.triggered.connect(app.quit)
self.setWindowIcon(QIcon('icon.ico'))
self.centralwidget = VideoPlayer()
self.setCentralWidget(self.centralwidget)
def keyPressEvent(self, QKeyEvent):
if QKeyEvent.key() == Qt.Key_Escape:
self.centralwidget.phaseQuit(2)
self.centralwidget.play()
class VideoPlayer(QWidget):
def __init__(self, parent=None):
super(VideoPlayer, self).__init__(parent)
self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
self.videoItem = QGraphicsVideoItem()
self.videoItem.setSize(QSizeF(640, 480))
scene = QGraphicsScene(self)
graphicsView = QGraphicsView(scene)
scene.addItem(self.videoItem)
layout = QVBoxLayout()
layout.addWidget(graphicsView)
self.setLayout(layout)
self.mediaPlayer.setVideoOutput(self.videoItem)
self.counter = 0
def play(self):
if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
pass
else:
self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(glob.glob("videos/*")[self.counter])))
self.mediaPlayer.play()
self.counter += 1
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
player = MainWindow()
player.show()
sys.exit(app.exec_())

How to change ipython qtconsole input

I'm making a guide with pyqt and I'm including an ipython qtconsole widget.
try:
from qtconsole.rich_jupyter_widget import RichJupyterWidget as ipythonWidget
from qtconsole.inprocess import QtInProcessKernelManager
except:
from IPython.qt.console.rich_ipython_widget import RichIPythonWidget as ipythonWidget
from IPython.qt.inprocess import QtInProcessKernelManager
I want to modify the qtconsole input from my code but is not working. I've tried the set_next_input function but it doesn't work and I can't find another function I can use to acomplish what I want. Is even possible to achieve what I want? and if so, how can I do it?
Here is my code:
try:
from qtconsole.rich_jupyter_widget import RichJupyterWidget as ipythonWidget
from qtconsole.inprocess import QtInProcessKernelManager
except:
from IPython.qt.console.rich_ipython_widget import RichIPythonWidget as ipythonWidget
from IPython.qt.inprocess import QtInProcessKernelManager
import sys
from PyQt4 import QtGui
class sympyIpython(QtGui.QWidget):
def __init__(self):
super().__init__()
self.ipython = IpythonWidget()
v = QtGui.QVBoxLayout(self)
button = QtGui.QPushButton('append to input')
v.addWidget(self.ipython)
v.addWidget(button)
button.clicked.connect(self.symClicked)
def symClicked(self):
self.ipython.kernel.shell.set_next_input(' appended text')
class IpythonWidget(ipythonWidget):
def __init__(self):
super().__init__()
self.kernel_manager = QtInProcessKernelManager()
self.kernel_manager.start_kernel()
self.kernel = self.kernel_manager.kernel
self.kernel.gui = 'qt4'
self.kernel_client = self.kernel_manager.client()
self.kernel_client.start_channels()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
m = sympyIpython()
m.show()
sys.exit(app.exec_())
Reposting as an answer:
To change the text at the prompt in the Qt console, set input_buffer on the widget object:
jupyter_widget.input_buffer = 'text'

Access untranslated string in PyQt?

I am writing a little pyqt application. Now I have start using Qtranslator with *.ts and *.qm files to get a Swedish translation.
I use e.g. self.tr(“Test this”) “Swedish Testar detta”. I am wondering while using the Swedish translation, if it is possible to get back the original untranslated string, in this case “Test this” in the program?
This i my little program and I want the "translate_string" method to print the original string.
from PyQt5.QtWidgets import (QApplication, QDialog, QPushButton, QVBoxLayout)
import sys
from PyQt5.QtCore import (QTranslator)
class Form(QDialog):
def __init__(self):
super(Form, self).__init__()
button = QPushButton(self.tr("&Close"))
self.test_lang = QPushButton(self.tr("Translate"))
self.string = self.tr("Test this")
layout = QVBoxLayout()
layout.addWidget(self.test_lang)
layout.addWidget(button)
self.setLayout(layout)
self.test_lang.clicked.connect(self.translate_string)
button.clicked.connect(self.close)
def translate_string(self):
print(self.string)
if __name__ == '__main__':
app = QApplication(sys.argv)
translator = QTranslator()
translator.load("test_trans_sv_SE.qm")
app.installTranslator(translator)
form = Form()
form.show()
sys.exit(app.exec_())