簡體   English   中英

python json 列表索引必須是整數或切片,而不是 str 錯誤

[英]python json list indices must be integers or slices, not str error

我正在制作游戲,我開始處理保存和加載部分,它應該根據 JSON 文件中的值更改一些文本,當我嘗試導入我構建的 giu 的 JSON 文件時,我收到此錯誤


    Traceback (most recent call last):
      File "save_test.py", line 112, in <module>
        object.process()
      File "save_test.py", line 65, in process  
        self.onclickFunction()
      File "save_test.py", line 83, in open_file
        import_text()
      File "save_test.py", line 91, in import_text
        importedText = data_load(['Text']['text'])
    TypeError: list indices must be integers or slices, not str

您將需要一個 JSON 文件,以便您可以導入它然后運行代碼
代碼:

# Imports
import sys
import pygame
import tkinter as tk
from tkinter import filedialog
import json

root = tk.Tk()
root.withdraw()

# Configuration
pygame.init()
fps = 60
fpsClock = pygame.time.Clock()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
font = pygame.font.SysFont('Arial', 40)

objects = []
importedText = "example text"

class Button():

    def __init__(self, x, y, width, height, buttonText='Button', onclickFunction=None, onePress=False):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.onclickFunction = onclickFunction
        self.onePress = onePress

        self.fillColors = {
            'normal': '#ffffff',
            'hover': '#666666',
            'pressed': '#333333',
        }

        self.buttonSurface = pygame.Surface((self.width, self.height))
        self.buttonRect = pygame.Rect(self.x, self.y, self.width, self.height)

        self.buttonSurf = font.render(buttonText, True, (20, 20, 20))

        self.alreadyPressed = False

        objects.append(self)

    def process(self):

        mousePos = pygame.mouse.get_pos()

        self.buttonSurface.fill(self.fillColors['normal'])
        if self.buttonRect.collidepoint(mousePos):
            self.buttonSurface.fill(self.fillColors['hover'])

            if pygame.mouse.get_pressed(num_buttons=3)[0]:
                self.buttonSurface.fill(self.fillColors['pressed'])

                if self.onePress:
                    self.onclickFunction()

                elif not self.alreadyPressed:
                    self.onclickFunction()
                    self.alreadyPressed = True

            else:
                self.alreadyPressed = False

        self.buttonSurface.blit(self.buttonSurf, [
            self.buttonRect.width/2 - self.buttonSurf.get_rect().width/2,
            self.buttonRect.height/2 - self.buttonSurf.get_rect().height/2
        ])
        screen.blit(self.buttonSurface, self.buttonRect)




def open_file():
    global importedText
    importedText = filedialog.askopenfilename(filetypes=(("Lil brute save file", "*.json"), ("All Files", "*.*")))
    import_text()



def import_text():
    global importedText
    f = open(importedText)
    data_load = json.load(f)
    importedText = data_load(['Text']['text'])


# set the center of the rectangular object.

customButton = Button(30, 30, 400, 100, 'import',open_file)


# Game loop.
while True:
    screen.fill((20, 20, 20))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    text = font.render(importedText, True, green, blue)
    # create a rectangular object for the
    # text surface object
    textRect = text.get_rect()
    textRect.center = (width  // 2, height // 2)
    for object in objects:
        object.process()
    screen.blit(text, textRect)
    pygame.display.flip()
    pygame.display.update()
    fpsClock.tick(fps)

JSON 文件: {"Text": {"text": "import successful"}}

您的代碼將 data_load 作為 function 調用,但它是一個字典。 將您的 import_text function 更改為:

def import_text():
    global importedText
    f = open(importedText)
    data_load = json.load(f)
    importedText = data_load['Text']['text']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM