#QLabel控件使用 from PyQt5.QtWidgets import QApplication,QLabel,QWidget,QVBoxLayout from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap,QPalette import sys import webbrowser class WindowDemo(QWidget): def __init__(self): super().__init__() self.label_1=QLabel(self) self.label_1.setText("這是一個文本標簽!<a href='www.baidu.com' style='color:red'>百度</a>") self.label_1.setAutoFillBackground(True) self.palette=QPalette() self.palette.setColor(QPalette.Window,Qt.blue) self.label_1.setPalette(self.palette) self.label_1.setAlignment(Qt.AlignCenter) self.label_1.setOpenExternalLinks(True) # 允許訪問超鏈接 self.label_1.linkHovered.connect(self.link_hovered) # 針對鏈接光標略過 self.label_1.linkActivated.connect(self.link_clicked) # 針對鏈接點擊事件 self.label_2=QLabel(self) self.label_2.setPixmap(QPixmap('./duck.png')) # 設置圖標,與文字沖突,則setText的文字不顯示 self.label_2.mousePressEvent = self.photo_link # 設置圖片點擊事件 self.vbox=QVBoxLayout() self.setLayout(self.vbox) self.vbox.addWidget(self.label_1) self.vbox.addWidget(self.label_2) self.vbox.addStretch() def photo_link(self, test): webbrowser.open('https://www.baidu.com/') def link_hovered(self): print("光標滑過Label_1觸發事件") def link_clicked(self): print("點擊時觸發事件") if __name__ == "__main__": app = QApplication(sys.argv) win = WindowDemo() win.show() sys.exit(app.exec_())