python错误 - TypeError: string indices must be integers(字符串索引必须是整数)

问题描述 投票:0回答:1

我一直在开发一个闪卡应用程序,在尝试实现单选按钮时遇到了一个障碍。问题是当运行时,菜单显示出来,你可以访问课程,但radiobuttons没有出现。每当代码运行时,都会出现以下错误。类型错误:字符串索引必须是整数。 附在radioobutton功能上balancing_radio_butto1 = Radiobutton(balancing_frame, text = balancing[answer_list[0]], variable=balancing_radio, value = 1) 如果有人能解释为什么会出现这个错误,以及如何解决它将是非常感激。下面是我的代码,到目前为止,我有。

from tkinter import *
from PIL import ImageTk, Image
from random import branding
import random

root = Tk()
root.title('Chemistry Flashcards')
root.geometry("500x500")


def balancing():
balancing_frame.pack(fill="both", expand=1)



global show_balancing
show_balancing = Label(balancing_frame)
show_balancing.pack(pady=15)

global balancing
balancing = ['balanced1', 'balanced2', 'balanced3', 'balanced4', 'balanced5', 'unbalanced1', 'unbalanced2', 'unbalanced3', 'unbalanced4', 'unbalanced5']

global balancing_state
balancing_state = {
'balanced1':'balanced',
'balanced2':'balanced',
'balanced3':'balanced',
'balanced4':'balanced',
'balanced5':'balanced',
'unbalanced1':'unbalanced',
'unbalanced2':'unbalanced',
'unbalanced3':'unbalanced',
'unbalanced4':'unbalanced',
'unbalanced5':'unbalanced',

}

answer_list = []
count = 1


while count < 3:
    rando = randint(0, len(balancing_state)-1)
    if count == 1:
        answer = balancing[rando]

        global balancing_image
        balancing = "C:/Users/Kisitu/Desktop/project/balancing/" + balancing[rando] + ".png"
        balancing_image = ImageTk.PhotoImage(Image.open(balancing))
        show_balancing.config(image=balancing_image)

    answer_list.append(balancing[rando])

    '''random.shuffle(balancing)'''
    count += 1

    random.shuffle(answer_list)

global balancing_radio
balancing_radio = IntVar()

balancing_radio_butto1 = Radiobutton(balancing_frame, text = balancing[answer_list[0]], variable=balancing_radio, value = 1)
balancing_radio_butto1.pack(pady=10)
balancing_radio_butto2 =  Radiobutton(balancing_frame, text = balancing[answer_list[1]], variable=balancing_radio, value = 2).pack()




my_menu = Menu(root)
root.config(menu=my_menu, bg='#B7F7BB')

lesson_menu = Menu(my_menu)
my_menu.add_cascade(label="Lesson", menu=lesson_menu)
lesson_menu.add_command(label="balancing", command=balancing)
lesson_menu.add_separator()
lesson_menu.add_command(label="Exit", command=root.quit)


balancing_frame = Frame(root, width=500, height=500, )



root.mainloop()
python string user-interface tkinter int
1个回答
1
投票

... text = balancing[answer_list[0]] ...

balancing是一个列表,你正试图从列表中索引一个值.你正在传递answer_list[0]作为索引.answer_list包含来自balancing的随机字符串.你正试图用一个字符串索引一个列表,如

balancing["balanced2"]

也许你可以用一本字典?

© www.soinside.com 2019 - 2024. All rights reserved.