【发布时间】:2013-12-29 15:06:07
【问题描述】:
我在这里遇到了一个棘手的问题。基本上我想做的是有一个类似 tamaguchi 的程序,人们可以选择 tamaguchi 的功能,它的大小要么增加,要么减小。这很有效,因为只有一个玉口!但是应该可以同时创建和管理多个 tamaguchi。不过,当我尝试这个时,我遇到了大问题。到目前为止,基本上这就是我的想法:
class Tamaguchi(object):
def __init__(self,name,size=1):
self.name=name
self.size=size
def increasesize(self):
self.size+=1
GoodBadChange.config(text="Good job. You increased in size!")
def decreasesize(self):
self.size-=1
GoodBadChange.config(text="Bad job. You decreased in size!")
def main():
print(name)
root = tkinter.Tk()
global root
root.title("Tamaguchi-spelet")
root.geometry("900x900")
getLists()
getPhotos()
Picture = tkinter.Label(root, image=normal)
Picture.pack()
global Picture
ScoreBoard = tkinter.Label(root, text="Score " + str(tamaguchin.size), font=('Helvetica', 15))
ScoreBoard.pack()
global ScoreBoard
GoodBadChange = tkinter.Label(root, text="", font=('Helvetica', 12))
GoodBadChange.pack()
global GoodBadChange
LatestAction = tkinter.Label(root, text="", font=('Helvetica', 12))
LatestAction.pack()
global LatestAction
app = Application(root)
app.pack()
updateDisplay()
LatestAction.config(text="Hello and welcome to the tamaguchi game!\nThe tamaguchi starts the day with the size "+str(tamaguchin.size)+"!\nThe tamaguchi starts the day off with the last three actions of "+lista[0]+"-"+lista[1]+"-"+lista[2]+"\n")
root.mainloop()
tamaguchi_list=[]
amount=int(input("Number of tamaguchis in your farm: "))
for i in range(amount):
name = input("What do you want to name your tamaguchis?: ")
tamaguchi_name = Tamaguchi(name)
tamaguchi_list.append(tamaguchi_name)
for tamaguchis in tamaguchi_list:
main()
for tamaguchis in tamaguchi_list:
print(name,"reached a size of ",name.size,"!")
对不起,有点长,我仍然缩短了不相关的部分。但我在想,我们创建一个包含所有 tamaguchi 的列表,然后我们只需为 tamaguchi-list 中的每个 tamaguchi 运行 main 函数。这样,例如“erik”得到一个分数,“mary”得到另一个分数,这应该写在最后。但是,这似乎不起作用,如您所见,我在 main 函数的开头写了“print(name)”,只是为了查看它实际上遍历了列表中的所有名称,但实际上它只是打印了一遍又一遍的同一个名字。我不知道为什么它没有通过所有名称。
另一个问题是,当我想显示 tamaguchi 的大小时,我已经在 str(tamaguchin.size) 之类的主函数中编写了这一事实,但这是因为当我只有一个 tamaguchi 时,我只是在一开始就创建了它,我可以在程序的其余部分中引用它(我曾经拥有的 tamguchin=Tamaguchi('SomeName') !)这可以解决吗?
非常感谢您的帮助,我真的很困惑。
编辑:也许不清楚,因为我没有显示所有代码。我认为它可能太长了,但也许最好理解我的意思! I uploaded it here!
【问题讨论】:
-
您的列表可能包含对同一个对象的引用,所以难怪所有名称都相同,因为它们实际上是相同的。
-
main从哪里获得像name和更重要的是tamaguchin这样的输入? -
事实上,主函数引用了“tamaguchin”之类的东西是该程序的遗物,仅适用于一个 tamaguchi。那时我刚开始创建了一个 tamaguchi,它的对象名称为“tamaguchin”。从那里很容易一直引用它。我知道它需要改变,我只是不知道如何或改变什么,如果我想要几个 tamaguchis :o name 来自输入,“name = input("你想给你的 tamaguchis 起什么名字?”)
-
这很可能是您问题的答案:您在某处定义了一个引用
tamaguchin,它只引用一个 tamaguchi,因此您总是会打印它的名称。为什么不将 tamaguchi 作为main的输入?否则,tamaguchis in tamaguchi_list:块的整个根本没有意义,因为您实际上并没有遍历 tamaguchis,即您对它们中的每一个都不做任何事情...您有问题吗? -
来自一位瑞典同胞:查看您的完整代码链接......永远不要使用除英语之外的任何东西来表示变量名、函数等。英语是编程的“通用语言”,如果您使用它获得帮助(和工作!)的机会将会增加。你显然对英语没有问题,所以用英语编程也不应该给你带来困难。 Bara som ett 小贴士 :)
标签: python