xia的小窩

一起來coding和碼字吧

0%

pyqt-按鈕變換詞句

空架

先處理背景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from PyQt6.QtWidgets import *
from PyQt6.QtGui import *
from PyQt6 import QtCore, QtGui
import sys

class root(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("實踐")
self.setWindowIcon(QIcon("Your picture"))


if __name__ == "__main__":
import sys
app = QApplication([])
window = root()
window.show()
sys.exit(app.exec())

目前的樣子

背景

有許多種方法

1
2
3
4
# 第一種
setStyleSheet("background-color: your-color")
# 第二種
setStyleSheet("background-image: your-image")

我們選擇第二種 :point_down:

1
2
3
4
5
6
7
8
9
# class內部
stylesheet = """
background-image: url("g.png");
background-position: center;
"""
self.setStyleSheet(stylesheet)

# 最下面
window.resize(640, 640)

結果

亂數

1
2
3
4
import random

# __init__()內部
self.hello = ["hello", "早安", "morning"]

按鈕

1
2
3
4
def BtnChange(self):
btn = QPushButton("click me", self)
btn.resize(500, 50)
btn.move(75, 550)

連線

1
2
# BtnChange()
btn.clicked.connect(self.changeDescribe)

接收信號

1
2
def changeDescribe(self):
self.label.setText(random.choice(self.hello))

文字

1
2
3
4
5
self.label = QLabel("test", self)
self.label.setGeometry(QtCore.QRect(265, 100, 600, 200))
#這行程式的意思是: QRect(x, y, 水平長度, 縱向長度)
self.label.setFont(QtGui.QFont('STIX Two Text', 80))
#這行程式是用於設定字體、大小

呼叫

1
2
# 在 __init__()裡呼叫
self.BtnChange()

成果

圖片範例