python - 一个变量是否有可能识别出它持有一个字典变量并相应地使用它
问题描述
我在 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_scroll
text_output = new_pokemon_dictionary[str(text_scroll_n)
无论如何我可以text_scroll(dictionary)
在我的整个代码中使用,只需输入我想用作参数的不同字典变量名,或者是为所有不同字典重写所需代码的唯一解决方案?
我是编码新手,如果有任何马虎,我很抱歉。
谢谢!
解决方案
所以据我所知,真正发生的事情是您将字符串传递"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)
推荐阅读
- typescript - 打字稿:从嵌套的全局对象访问值 | 类型“字符串”不能用作索引类型
- c# - 迁移异常 - 无法创建唯一索引
- java - 使用 testng 从并行运行测试切换到串行测试执行
- excel - 多次写入 NOTEempty 单元格
- gstreamer - Twilio 拒绝 WebRTC SDP
- continuous-integration - CircleCI 工作流程未按预期工作
- python - 用于存储具有频率的项目列表的 Python 结构
- typescript - 如何为多个区分联合编写数组类型?
- ajax - 按 Woocommerce 价格表排序
- android - 如何触发发出 livedata 对象的函数?