【发布时间】:2021-03-08 07:41:21
【问题描述】:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys, time, threading
class Main_(QMainWindow):
def __init__(self, *args, **kwargs):
super(Main_, self).__init__(*args, **kwargs)
self.resize(QSize(300, 250))
self.show()
def change_window_title(self, title):
self.setWindowTitle(title)
def fctn(title_fctn):
print('START')
time.sleep(5)
title_fctn('Test')
print('DONE')
app = QApplication(sys.argv)
window = Main_()
# Method 1
fctn(window.change_window_title)
# Method 2
threading.Thread(
target=lambda: window.change_window_title('test')
).start()
# Method 3
threading.Thread(
target=lambda: fctn(window.change_window_title)
).start()
app.exec()
我想更改窗口的标题。为此,我使用了 3 种方法:
- 方法一:直接调用函数
- 方法二:在不同的线程中直接调用函数
- 方法 3: 在包装函数中调用该函数,然后在不同的线程中调用该包装函数。
注意:我不知道我为什么使用method 3,但令人震惊的是为什么method 2 和method 3 运行方式不同。 为什么?
Method 2 冻结了应用程序,而Method 3 工作完全正常。 我认为两者都会给出相同的结果,但事实并非如此。如果有人能给出适当的解释,那将是一个很大的帮助。
【问题讨论】:
-
在 linux 中使用方法 2 我没有看到任何冻结
-
@eyllanesc 您的代码是否使用方法 2 完美运行(更改了标题并且没有冻结)?因为我在windows上,只有方法3有效
标签: python python-3.x multithreading pyqt pyqt5