You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt5:将按钮动作移入QThread独立线程时的属性报错解决问询

PyQt5多线程改造报错求助

我是Python GUI及多线程编程新手,若术语表述不够准确,提前致歉。

原PyQt5 GUI代码

import PyQt5
import automation_main
from PyQt5.QtWidgets import *  # 修正原代码拼写错误:QtWdigets → QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Test')  # 修正原代码拼写错误:setWindowTite → setWindowTitle
        self.setGeometry(100, 100, 500, 800)  # 补充窗口高度,避免按钮位置超出可视范围
        self.UiComponents()
        self.UiWidgets()
        self.show()

    def UiComponents(self):
        button1 = QPushButton('Hello', parent=self) 
        button1.setGeometry(120, 670, 150, 50)
        button1.clicked.connect(self.clickme)

    def UiWidgets(self):
        # 用户输入年份的文本框
        self.textbox = QLineEdit(self)
        self.textbox.setGeometry(185, 140, 450, 40)
        self.textbox.returnPressed.connect(self.entered)

        # 用户选择月份的下拉框
        self.combobox = QComboBox(self)
        self.combobox.setGeometry(185, 255, 450, 40)
        options = ['Jan', 'Feb', 'Mar']
        self.combobox.setEditable(True)
        self.combobox.addItems(options)
        line_edit = self.combobox.lineEdit()
        line_edit.setAlignment(Qt.AlignCenter)
        line_edit.setReadOnly(True)
        self.combobox.activated[str].connect(self.selected)

    def entered(self):
        # 存储用户输入的年份
        self.entered_text = int(self.textbox.text())
    
    def selected(self, text):
        # 存储用户选择的月份
        self.selected_text = text

    def clickme(self):
        # 调用外部自动化函数
        year_loc = automation_main.main(self.selected_text, self.entered_text)

我的尝试步骤

  1. 创建Worker类,将业务逻辑移入其中:
class Worker(QObject):
    finished = pyqtSignal()
    progress = pyqtSignal(int)
    
    def clickme(self, x, y):  # 补充self参数,修正原代码缺失问题
        year_loc = automation_main.main(x, y)
  1. 在Window类中添加线程创建方法,并在构造函数中调用:
def createWorkerThread(self):  # 修正原代码拼写错误:createWrokerThread → createWorkerThread
    self.worker = Worker()
    self.worker_thread = QThread()
    self.worker.moveToThread(self.worker_thread)
    self.worker_thread.start()

# 构造函数中调用线程创建方法
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Test')
        self.setGeometry(100, 100, 500, 800)
        self.createWorkerThread()
        self.UiComponents()
        self.UiWidgets()
        self.show()
  1. 修改按钮的点击事件绑定:
def UiComponents(self):
    button1 = QPushButton('Hello', parent=self) 
    button1.setGeometry(120, 670, 150, 50)
    button1.clicked.connect(lambda: self.worker.clickme(self.entered_text, self.selected_text))

遇到的问题

运行时出现错误提示:'Window' has no attribute 'entered_text',恳请协助解决该问题。


内容的提问来源于stack exchange,提问作者user20893826

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 23:35:40