首页 > 解决方案 > 一个变量是否有可能识别出它持有一个字典变量并相应地使用它

问题描述

我在 python 3 中使用 tkinter 制作了一个简单的游戏,其中包括我制作的一个函数,每次单击按钮时都会遍历文本部分的字典。

new_pokemon_dictionary = {
"1": "It's a new pokemon!", "2": "Are you ready to fight it?"#, "3": "3rd piece of text etc
}
text_scroll_n=0
def next_button():
    global text_scroll_n

    textbox.delete(0.0, END)
    text_scroll_n+=1  #Every time next_button run adds 1, this makes it print new part of the dictionary            

    if game_stage == 1:
        text_scroll("new_pokemon_dictionary")
    else:
        return
    textbox.insert(END, text_output)
    screen.update()

通过单击下一个按钮,该按钮text_scroll_n将增加一,并由该text_scroll功能用于选择要显示的字典的新部分:

def text_scroll(dictionary):

    if text_scroll_n<=len(dictionary):
        print(dictionary)
        text_output = dictionary[str(text_scroll_n)] #Textbox will insert at end of next_button function
    else:
        game_stage +=1 

但是,在运行此程序时(以及未显示的其他代码部分,例如创建 texbox),我得到了错误:TypeError: string indices must be integers.

我假设这是因为它试图设置text_output为一个字母 in dictionary,其在单词中的位置等于 text_scroll_n 的整数。

但是,当我用它替换函数text_output = dictionary[str(text_scroll_n)]中的行时,它可以完美地工作,认识到 new_pokemon_ditrionary 变量是一个字典。text_scrolltext_output = new_pokemon_dictionary[str(text_scroll_n)

无论如何我可以text_scroll(dictionary)在我的整个代码中使用,只需输入我想用作参数的不同字典变量名,或者是为所有不同字典重写所需代码的唯一解决方案?

我是编码新手,如果有任何马虎,我很抱歉。
谢谢!

标签: python

解决方案


所以据我所知,真正发生的事情是您将字符串传递"new_pokemon_dictionary"text_scroll函数,而不是字典new_pokemon_dictionary。每次text_scroll通话都不要引号,你应该没问题。

所以这...

if game_stage == 1:
        text_scroll("new_pokemon_dictionary")

...变成这个

if game_stage == 1:
        text_scroll(new_pokemon_dictionary)

推荐阅读