[Python/PyQt] PyQt button click 이벤트

leesoyeon·2023년 7월 7일
0

PyQt

목록 보기
2/4

📌 PyQt button click 이벤트

📃 문제

'CLICK' 버튼을 눌렀을 때 'Good Morning' 이 'Good Evening' 으로 바뀌는 코드를 작성하시오.


📁 myqt01.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>777</width>
    <height>561</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QPushButton" name="pb">
    <property name="geometry">
     <rect>
      <x>280</x>
      <y>270</y>
      <width>231</width>
      <height>61</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <family>둥근모꼴</family>
      <pointsize>20</pointsize>
      <weight>50</weight>
      <bold>false</bold>
     </font>
    </property>
    <property name="text">
     <string>CLICK</string>
    </property>
   </widget>
   <widget class="QLabel" name="lbl">
    <property name="geometry">
     <rect>
      <x>200</x>
      <y>150</y>
      <width>411</width>
      <height>101</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <family>둥근모꼴</family>
      <pointsize>48</pointsize>
     </font>
    </property>
    <property name="text">
     <string>Good Morning</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>777</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

📁 myqt01.py

from PyQt5 import QtWidgets, uic
import sys
form_window = uic.loadUiType("myqt01.ui")[0]

class UiMainWindow(QtWidgets.QMainWindow, form_window):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.show()
        self.pb.clicked.connect(self.myclick)

    def myclick(self):
        self.lbl.setText("Good Evening")
        
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    main_window = UiMainWindow()
    sys.exit(app.exec_())   


💻 결과


💡 POINT

  • self.buttonName.clicked.connect(function)
    객체 클릭 시 함수로 연결되어 이벤트 발생

  • setText()
    기존의 text 값을 지우고 새로운 text 값을 셋팅

0개의 댓글

관련 채용 정보