python - 在 Python3 中将小部件应用程序作为线程启动?
问题描述
Python3
尝试运行一些执行以下操作的代码:
- 使用 Threading 模块创建两个线程。
- 从 PyQt5.QtWidgets 模块启动 QApplication。
我试过先启动应用程序并使用应用程序启动线程——不幸的是,我对QtWidgets不太熟悉。
这是代码:
import time
import sys
import threading
from PyQt5.QtWidgets import *
def main():
pass
# THREADING Function 1
def print_interval( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print( "%s: %s" % ( threadName, tm.ctime(time.time()) ))
#THREADING Function 2
def startAPP():
app = QApplication([])
app.setStyle('Fusion')
window = QWidget()
layout = QVBoxLayout()
layout.addWidget(QPushButton('Top'))
layout.addWidget(QPushButton('Bottom'))
layout.addWidget(QFontDialog('Left'))
window.setLayout(layout)
window.show()
app.exec_()
if __name__ == '__main__':
for x in range(0, 4):
sys.stdout.write('\r'+"Loading" + "." * x)
time.sleep(1)
main()
# Create two threads as follows
try:
thread1 = threading.Thread()
thread1.target = print_interval('name',4)
thread1.start()
thread2 = threading.Thread()
thread2.target = startAPP()
thread2.start()
except:
print("Error: unable to start thread")
while 1:
pass
解决方案
您至少有以下错误:
您不能将评估函数传递给目标,但它是可调用的,在您的情况下,目标是评估函数。
出于设计原因,Qt 禁止在辅助线程上运行 GUI,因此第二个线程是不必要的,您必须更改它而不是 while True。
QFontDialog 期望 QFont 或 QWidget 或两者作为参数,但不是字符串。
import time
import sys
import threading
from PyQt5.QtWidgets import *
def main():
pass
# THREADING Function 1
def print_interval(threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("%s: %s" % (threadName, time.ctime(time.time())))
# THREADING Function 2
def startAPP():
app = QApplication([])
app.setStyle("Fusion")
window = QWidget()
layout = QVBoxLayout()
layout.addWidget(QPushButton("Top"))
layout.addWidget(QPushButton("Bottom"))
layout.addWidget(QFontDialog())
window.setLayout(layout)
window.show()
app.exec_()
if __name__ == "__main__":
for x in range(0, 4):
sys.stdout.write("\r" + "Loading" + "." * x)
time.sleep(1)
main()
# Create two threads as follows
try:
thread = threading.Thread(target=print_interval, args=("name", 1))
thread.start()
except:
print("Error: unable to start thread")
startAPP()
推荐阅读
- gitlab - 自托管 Gitlab 无效的 reCaptcha 密钥类型
- reactjs - 如何在反应中使用钩子将数组从子组件传递到父组件
- firebase - 实施 Firestore 时,Flutter Web 应用程序不会加载
- python - 使用 tensorflow 2.3 的 rgb_to_grayscale,得到“尺寸必须相等的错误”
- javascript - 在 ASP.Net MVC 中登录后显示 HTML 内容
- laravel - Laravel Resources 路由性能或收益
- python - multiprocessing.Process 从进程创建行到行尾重复调用主函数?
- mysql - 如何在mysql中的虚拟列上添加条件?
- r-raster - 在 R 错误中重新投影栅格“找不到函数”wkt
- python - 如何使用 OOP 在 Tkinter 中制作多个帧?