[Python/PyQt] PyQt 버튼 클릭 시 숫자 감소 예제

leesoyeon·2023년 7월 7일
0

PyQt

목록 보기
3/4

📌 PyQt button click 이벤트

📃 문제

'DECREASE' 버튼을 눌렀을 때 숫자가 1씩 감소되는 코드를 작성하시오.


📁 myqt02.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>280</width>
    <height>235</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QLineEdit" name="le">
    <property name="geometry">
     <rect>
      <x>50</x>
      <y>50</y>
      <width>181</width>
      <height>41</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <family>둥근모꼴</family>
      <pointsize>24</pointsize>
     </font>
    </property>
    <property name="layoutDirection">
     <enum>Qt::LeftToRight</enum>
    </property>
    <property name="autoFillBackground">
     <bool>false</bool>
    </property>
    <property name="text">
     <string>100</string>
    </property>
    <property name="frame">
     <bool>true</bool>
    </property>
    <property name="alignment">
     <set>Qt::AlignCenter</set>
    </property>
   </widget>
   <widget class="QPushButton" name="pb">
    <property name="geometry">
     <rect>
      <x>50</x>
      <y>120</y>
      <width>181</width>
      <height>31</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <family>둥근모꼴</family>
      <pointsize>20</pointsize>
     </font>
    </property>
    <property name="text">
     <string>DECREASE</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>280</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

📁 myqt02.py

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

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

    def decreaseNum(self):
        txt = self.le.text()
        num = int(txt)
        txt2 = str(num-1)
        self.le.setText(txt2)
        
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    main_window = UiMainWindow()
    sys.exit(app.exec_())


💻 결과


💡 POINT

  • self.object.text()
    객체의 text 값을 가져온다

    String 타입이기 때문에 연산을 하기 위해선 형 변환 필수
    연산 후 setText() 로 값을 다시 넣어줄 때도 잊지 말고 형 변환하기!

0개의 댓글

관련 채용 정보