컴퓨터/Python

python pyside6 그림 이미지 순환

풍경소리^^ 2023. 12. 2. 08:16
import sys

from PySide6.QtGui import QPixmap
from PySide6.QtWidgets import QApplication, QLabel, QMainWindow
from random import choice

imgs = ["otje.jpg","통영항.jpg","하트.jpg"] #

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("My App")

        self.widget = QLabel("Hello")
        # widget.setPixmap(QPixmap(choice(imgs))) #
        self.widget.setPixmap(QPixmap("otje.jpg")) #
        # self.origin_photo = True  # 추가
        self.num = 0
        self.widget.mousePressEvent = self.photo_toggle  # 추가

        self.setCentralWidget(self.widget)
    
    def photo_toggle(self, event):  # 추가
        # if self.origin_photo:
        #     self.widget.setPixmap(QPixmap(imgs[1]))
        #     self.origin_photo = False
        # else:
        #     self.widget.setPixmap(QPixmap(imgs[0]))
        #     self.origin_photo = True
        self.num = (self.num + 1) % len(imgs)
        # print(self.num)
        self.widget.setPixmap(QPixmap(imgs[self.num]))


app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()

다른 경로에서 실행할 경우

import os
import sys

from PySide6.QtGui import QPixmap
from PySide6.QtWidgets import QApplication, QLabel, QMainWindow

basedir = os.path.dirname(__file__)

imgs = ["otje.jpg","통영항.jpg","고현정.jpg"] #
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("My App")

        self.widget = QLabel("Hello")
        # tag::scaledContents[]
        self.widget.setPixmap(QPixmap(os.path.join(basedir, "otje.jpg")))
        self.widget.setScaledContents(True)
        # end::scaledContents[]

        self.setCentralWidget(self.widget)

        # self.origin_photo = True  # 추가
        self.num = 0
        self.widget.mousePressEvent = self.photo_toggle  # 추가
    
    def photo_toggle(self, event):  # 추가
        # if self.origin_photo:
        #     self.widget.setPixmap(QPixmap(imgs[1]))
        #     self.origin_photo = False
        # else:
        #     self.widget.setPixmap(QPixmap(imgs[0]))
        #     self.origin_photo = True
        self.num = (self.num + 1) % len(imgs)
        # print(self.num)
        self.widget.setPixmap(QPixmap(os.path.join(basedir,imgs[self.num])))


app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()