gpt4 book ai didi

python - 在 Python3 中将小部件应用程序作为线程启动?

转载 作者:行者123 更新时间:2023-12-01 06:36:28 24 4
gpt4 key购买 nike

Python3

尝试运行一些执行以下操作的代码:

  1. 使用 Threading 模块创建两个线程。
  2. 从 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()

关于python - 在 Python3 中将小部件应用程序作为线程启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59646077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com