|
发表于 2024-3-26 06:49:14
|
显示全部楼层
您遇到的错误是因为代码中并没有定义变量 `format`,也缺少了对 `QTextCharFormat` 的实例化。另外,在方法内部使用 `self` 前缀需要确保该方法是类的成员方法。以下是修改后的代码示例:
- from PySide6.QtWidgets import QApplication
- from PySide6.QtGui import QTextCharFormat, QColor
- from PySide6.QtCore import Qt
- class MyClass:
- def __init__(self):
- self.app = QApplication()
- def print_with_color_format(self, text1, variable, text2, color1, color2, color3):
- format = QTextCharFormat() # 实例化 QTextCharFormat
- format.setForeground(QColor(color1))
- print(text1, end='')
- format.clearForeground()
- format.setForeground(QColor(color2))
- print(variable, end='')
- format.clearForeground()
- format.setForeground(QColor(color3))
- print(text2)
- format.clearForeground()
- def run(self):
- Base_Workbook = 'example.xlsx'
- self.print_with_color_format('工作簿《', Base_Workbook, '》命名为《123.xls》', 'yellow', 'blue', 'yellow')
- self.app.quit()
- my_instance = MyClass()
- my_instance.run()
复制代码
请注意,在实例化 `QApplication` 后,我们将其保存在 `self.app` 中以便在方法中进行调用,并且在程序结束后调用了 `app.quit()` 来退出应用程序。
希望这次回答能满足您的要求!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|