You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt5技术问题:如何向单个QLabel追加多个生成的密码字符串

解决QLabel仅显示最后一个生成密码的问题

你的代码里有两个核心问题导致只能看到最后一个密码:

  • 每次外层循环都会重置self.passwords为空字符串,而且生成一个密码就立刻调用setText覆盖之前的内容;
  • 内层生成单个密码的循环里也重复调用setText,完全没必要,还会导致界面频繁刷新。

直接修改execute方法即可解决,思路是先把所有生成的密码收集到列表里,最后一次性把所有密码用换行符拼接后设置给QLabel:

def execute(self):
    char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()-_,./?'
    number_v = int(self.dialog1.textValue())
    length_v = int(self.dialog2.textValue())
    # 初始化列表存储所有密码
    all_passwords = []
    for _ in range(number_v):
        password = ''
        for _ in range(length_v):
            password += random.choice(char)
        # 把生成的单个密码加入列表
        all_passwords.append(password)
        print(password)
    # 用换行符拼接所有密码,设置给QLabel
    self.textBox.setText('\n'.join(all_passwords))
    # 可选:让QLabel自动换行,避免过长密码超出窗口
    self.textBox.setWordWrap(True)

另外还可以优化几点,提升程序稳定性和友好度:

  • 把字符集定义成类常量,不用每次调用execute都重新创建;
  • 给输入框设置数字输入模式,避免用户输入非数字内容导致报错;
  • 给QLabel设置默认提示文本,让界面更直观。

修改后的完整代码:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QVBoxLayout, QPushButton, QLabel
import random


class App(QWidget):
    # 把字符集设为类常量,复用更高效
    CHAR_SET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()-_,./?'
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Password Generator')
        self.setGeometry(100,100, 400, 400)
        self.intro = QLabel("Welcome to PyPass Gen 2.0")
        self.dialog1 = QInputDialog()
        self.dialog1.setOption(QInputDialog.NoButtons)
        self.dialog1.setLabelText('Number of passwords: ')
        # 设置输入框只接受数字
        self.dialog1.setInputMode(QInputDialog.IntInput)
        self.dialog2 = QInputDialog()
        self.dialog2.setOption(QInputDialog.NoButtons)
        self.dialog2.setLabelText('Length of passwords: ')
        self.dialog2.setInputMode(QInputDialog.IntInput)
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.intro, alignment=Qt.AlignCenter)
        self.layout.addWidget(self.dialog1)
        self.layout.addWidget(self.dialog2)
        self.textBox = QLabel("点击下方按钮生成密码")
        self.textBox.setWordWrap(True)  # 开启自动换行
        self.layout.addWidget(self.textBox, alignment=Qt.AlignCenter)
        self.button1 = QPushButton("Generate Passwords")
        self.button1.clicked.connect(self.execute)
        self.layout.addWidget(self.button1)

        self.setLayout(self.layout)
        self.show()

    def execute(self):
        number_v = self.dialog1.intValue()
        length_v = self.dialog2.intValue()
        all_passwords = []
        for _ in range(number_v):
            password = ''
            for _ in range(length_v):
                password += random.choice(self.CHAR_SET)
            all_passwords.append(password)
            print(password)
        self.textBox.setText('\n'.join(all_passwords))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

这样修改后,生成的所有密码会以每行一个的形式显示在QLabel里,同时也避免了非数字输入导致的程序崩溃问题。

内容的提问来源于stack exchange,提问作者AmeriNam20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 13:15:27