-1
私は、動物が配列内に格納された環境でランダムに移動するプログラムを作成しようとしています。私はこれをtkinterのキャンバス上でグラフィカルに表現しようとしていますが、キャンバスは単純に何も表示していません。私が読んだところでは、これを修正するために 'アフター'メソッドを使うことができると思われますが、これを自分のプログラムにどのように統合するのか分かりません。Tkinterキャンバスが更新されない
ご協力いただければ幸いです。
import random
from tkinter import*
class Animal():
def __init__(self,x,y):
self.x = x
self.y = y
class Enviroment():
def __init__(self):
self.GUI = GUIcontainer(self)
self.boardSize = 100
self.template = self.setUpTemplate()
self.GUI.setup()
def setUpTemplate(self):
template = []
for x in range(0,self.boardSize+1):
template.append([])
for y in range(0,self.boardSize+1):
template[x].append("N")
return template
def placeAnimals(self):
print("Placing")
for x in range(0,self.boardSize+1):
for y in range(0,self.boardSize+1):
if random.randint(0,10) == 5 and self.template == "N":
obj = Animal(x,y)
self.template[x][y] = obj
self.GUI.moveOrPlaceObj(obj,x,y)
def moveAnimals(self):
print("Moving")
for x in range(0,self.boardSize+1):
for y in range(0,self.boardSize+1):
if self.template[x][y] != "N":
obj = self.template[x][y]
dirction = random.randint(0,3)
if direction == 0 and y>5:
if self.template[x][y-5] == "N":
self.template[x][y-5] = obj
self.GUI.moveOrPlaceObj(obj,x,y-5)
self.template[x][y] = "N"
elif direction == 1 and x>5:
if self.template[x-5][y] == "N":
self.template[x-5][y] = obj
self.GUI.moveOrPlaceObj(obj,x-5,y)
self.template[x][y] = "N"
elif direction == 2 and y<95:
if self.template[x][y+5] == "N":
self.template[x][y+5] = obj
self.GUI.moveOrPlaceObj(obj,x,y+5)
self.template[x][y] = "N"
elif direction == 3 and x<95:
if self.template[x+5][y] == "N":
self.template[x+5][y] = obj
self.GUI.moveOrPlaceObj(obj,x+5,y)
self.template[x][y] = "N"
class GUIcontainer(object):
def __init__(self,enviro):
self.root = Tk()
self.Enviroment = enviro
self.widgetCreator = GUIwidgetCreator(self.root)
self.entryWidgets = []
self.statLabels = []
self.root.title("Simulation")
def setup(self):
self.widgetCreator.createButton("Start",(lambda event: self.startSim()),2,2)
self.canvas = self.widgetCreator.createCanvas(3,3,100,100,"black")
self.root.mainloop()
def startSim(self):
self.Enviroment.placeAnimals()
self.Enviroment.moveAnimals()
def moveOrPlaceObj(self,obj,x,y):
self.canvas.delete(obj)
self.canvas.create_line(x+0.5,y+0.5,x-0.5,y-0.5,fill="green",tag=obj)
#self.canvas.create_line(x+0.5,y+0.5,x-0.5,y-0.5,fill=obj.colour,tag=obj)
#self.canvas.after(100, self.moveOrPlaceObj)
self.canvas.update_idletasks()
class GUIwidgetCreator(object):
def __init__(self,root):
self.root = root
def createButton(self,txt,cmd,x,y):
self.button = Button(self.root)
self.button.config(text=txt)
self.button.bind("<Button-1>",cmd)
self.button.grid(column=x,row=y)
def createCanvas(self,x,y,height,width,colour):
self.canvas = Canvas(self.root)
self.canvas.config(height=height,width=width)
self.canvas.config(bg=colour)
self.canvas.grid(column=x,row=y)
return self.canvas
if __name__ == "__main__":
program = Enviroment()
'moveOrPlaceObj'は決して呼び出されません。あなたはprintステートメントを入れて確認できます。 –