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

如何为PySimpleGUI指定标签页设置访问密码验证?

PySimpleGUI标签页密码验证实现方案

需求说明

需要在PySimpleGUI的标签组中设置部分标签页可直接访问,其余标签页每次点击时需验证密码才能查看:

  • 可直接访问:Mobiles(标签1)、Computers(标签3)
  • 需密码验证:Tablettes、Televisions,验证密码为2022

原始代码问题分析

原代码存在以下关键问题:

  • 标签索引(数字)与可访问列表(字符串)的判断逻辑不匹配,导致无法正确识别可访问标签
  • 标签切换的组件引用方式错误,无法完成正常切换
  • 密码输入无隐藏显示,安全性不足

修正后的代码

import PySimpleGUI as sg

# 定义无需验证的标签名称列表
accessible_tabs = ['Mobiles', 'Computers']

# 构建标签组布局
layout = [
    [sg.TabGroup([
        [
            sg.Tab('Mobiles', [[sg.Text('This is the Tab 1')]], key='-TAB-MOBILES-'),
            sg.Tab('Tablettes', [[sg.Text('This is the Tab 2')]], key='-TAB-TABLETTES-'),
            sg.Tab('Computers', [[sg.Text('This is the Tab 3')]], key='-TAB-COMPUTERS-'),
            sg.Tab('Televisions', [[sg.Text('This is the Tab 4')]], key='-TAB-TELEVISIONS-')
        ]
    ], selected_title_color='yellow', key='-TABGROUP-')]
]

window = sg.Window('Tab Group', layout, finalize=True)
# 绑定标签点击事件,阻止默认切换行为
window['-TABGROUP-'].bind('<Button-1>', ' Click', propagate=False)

while True:
    event, values = window.read()
    
    if event == sg.WIN_CLOSED:
        break
    
    elif event == '-TABGROUP- Click':
        event_obj = window['-TABGROUP-'].user_bind_event
        # 确认点击的是标签标题区域
        if event_obj.widget.identify(event_obj.x, event_obj.y) == 'label':
            # 获取点击的标签索引
            tab_index = event_obj.widget.index(f'@{event_obj.x},{event_obj.y}')
            # 获取标签的标题文本
            tab_title = event_obj.widget.tab(tab_index, 'text')
            
            # 判断是否为可直接访问标签
            if tab_title in accessible_tabs:
                event_obj.widget.select(tab_index)
            else:
                # 弹出密码输入框,隐藏输入内容
                input_password = sg.popup_get_text("请输入密码", password_char='*')
                if input_password == '2022':
                    event_obj.widget.select(tab_index)
                else:
                    sg.popup("密码错误,无法访问该标签页")

window.close()

关键修正点说明

  1. 逻辑匹配修正:通过点击索引获取标签标题文本,再与可访问列表对比,解决原代码类型不匹配问题
  2. 正确切换标签:直接调用tkinter原生的select(tab_index)方法完成标签切换,避免组件引用错误
  3. 安全性优化:密码输入框添加password_char='*'隐藏输入内容,同时增加错误提示
  4. 代码规范:使用PySimpleGUI推荐的Key命名规范,修正拼写错误,提升代码可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:05:20