图片地址在E:\Python\Coding\controls\images 程序app.setWindowIcon(QIcon(r'\controls\images\001.ico')) 程序怎么才能用相当路径?
时间: 2023-11-17 22:00:13 浏览: 31
根据提供的引用内容,可以使用类似的方法来使用相对路径。首先,需要使用 os.path.dirname 获取包含文件夹 file,其中包含当前 Python 文件的完整路径。然后,使用 os.path.join() 方法来构建图标的相对路径。最后,将相对路径传递给 QIcon() 方法即可。具体代码如下所示:
```
import os
from PySide6 import QtWidgets, QtGui
basedir = os.path.dirname(__file__)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Hello World")
l = QtWidgets.QLabel("My simple app.")
l.setMargin(10)
self.setCentralWidget(l)
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon(os.path.join(basedir, 'controls', 'images', '001.ico')))
w = MainWindow()
app.exec()
```
在这个例子中,我们假设程序文件位于 E:\Python\Coding\controls 文件夹中,图标文件位于 E:\Python\Coding\controls\images 文件夹中。因此,我们使用 os.path.join() 方法来构建相对路径 controls/images/001.ico,并将其传递给 QIcon() 方法。