Skip to main content
 首页 » 编程设计

python之PyQt : How to change a label text from a package

2025年02月15日9zhujiabin

我的问题是: 如何更改包装中的标签(或其他图形元素)? 这个想法是为了减轻我的主要计划。 谢谢!

前主程序:

#../mainprogram.py 
#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
 
from PyQt5 import QtWidgets 
from ui import Ui_MainWindow 
from package import update 
 
class MainWindow(QtWidgets.QMainWindow): 
    def __init__(self): 
        super(MainWindow, self).__init__() 
        self.ui = Ui_MainWindow() 
        self.ui.setupUi(self) 
 
        # label from .ui -> .py 
        self.ui.label_1.setText("need to change this") 
 
    def update_label(self): 
        self.update = update.label_update() 

前包装:

#../package/update.py 
#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
 
def label_update(): 
    self.ui.label_1.setText("no problem") 

请您参考如下方法:

您需要做的是将对象的实例传递给函数。考虑:

def label_update(): 
    self.ui.label_1.setText("no problem") 

在这个范围内,我们不知道 self 是什么,因为它还没有被定义。但是,如果您通过 self 传递:

#../mainprogram.py 
class MainWindow(QtWidgets.QMainWindow): 
    def update_label(self): 
        self.update = update.label_update(self) 
 
 
#../package/update.py 
def label_update(obj): #obj is the object self 
    obj.ui.label_1.setText("no problem") 

我们正在更新传递给函数的对象。