PySimpleGUI中Text对象下标实现及报错'Text object is not subscriptable'问询
PySimpleGUI 问题解决:Text对象下标错误与下标文本实现
问题描述
- 运行代码时触发
TypeError: 'Text' object is not subscriptable错误,已在函数外定义文本变量但无法正常显示。 - 希望了解如何使用Text对象(或其他显示文本的对象)实现下标文本。
触发错误的代码
import PySimpleGUI as sg font1 = ("Calibri", 15) text1 = "PlaceholderText1" text2 = "PlaceholderText2" text3 = "PlaceholderText3" text4 = "PlaceholderText4" text5 = "PlaceholderText5" text6 = "PlaceholderText6" text7 = "PlaceholderText7" text8 = "PlaceholderText8" text9 = "PlaceholderText9" text10 = "PlaceholderText10" def stock(): layout = [[sg.Text("Our Stock:", font=font1) [sg.Text(text1)] [sg.Text(text2)] [sg.Text(text3)] [sg.Text(text4)] [sg.Text(text5)] [sg.Text(text5)] [sg.Text(text6)] [sg.Text(text7)] [sg.Text(text8)] [sg.Text(text9)] [sg.Text(text10)]]] window = sg.Window("Our Stock", layout, modal=True, size=(250, 300)) choice = None while True: event, values = window.read() if event == "Exit" or event == sg.WIN_CLOSED: break window.close() def lobbyWindow(): layout = [[sg.Text("What do you want to buy?")], [sg.Input(key='INPUT1')], [sg.Button("View Stock"), sg.Button("Exit"), sg.Button("Admin Panel")]] window = sg.Window("The Store", layout) while True: event, values = window.read() if event == "Exit" or event == sg.WIN_CLOSED: break if event == "View Stock": stock() window.close() lobbyWindow()
错误原因与修复
TypeError 错误修复
报错的核心是布局定义的语法错误:
stock()函数的layout中,第一个sg.Text("Our Stock:", font=font1)后面缺少逗号,导致Python将后续的[sg.Text(text1)]解析为对Text对象的下标操作(即试图执行sg.Text(...)[]),触发'Text' object is not subscriptable错误。- 布局嵌套结构错误:原代码将所有Text行塞进同一个外层列表,而PySimpleGUI要求每行是独立的子列表。
修复后的stock()函数代码:
def stock(): # 修复布局语法:每行一个子列表,元素间用逗号分隔 layout = [ [sg.Text("Our Stock:", font=font1)], [sg.Text(text1)], [sg.Text(text2)], [sg.Text(text3)], [sg.Text(text4)], [sg.Text(text5)], [sg.Text(text5)], [sg.Text(text6)], [sg.Text(text7)], [sg.Text(text8)], [sg.Text(text9)], [sg.Text(text10)] ] window = sg.Window("Our Stock", layout, modal=True, size=(250, 300)) choice = None while True: event, values = window.read() if event == "Exit" or event == sg.WIN_CLOSED: break window.close()
下标文本实现方法
在PySimpleGUI中实现下标文本,有两种常用方式:
1. 使用Unicode下标字符
直接使用Unicode标准中的下标字符,无需特殊字体,兼容性强:
# 示例:显示H₂O sg.Text("H₂O") # 自定义下标文本:PlaceholderText₁ text1_sub = "PlaceholderText₁" sg.Text(text1_sub)
常用下标字符对应:₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵧ
2. 使用富文本(仅支持Qt后端)
如果使用Qt作为PySimpleGUI的后端,可通过HTML-like标签实现下标:
import PySimpleGUIQt as sg # 使用<sub>标签定义下标 sg.Text("H<sub>2</sub>O", enable_events=True)
内容的提问来源于stack exchange,提问作者Dev
相关产品推荐
相关产品推荐

